/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
    http://www.JSON.org/json2.js
    2010-11-17

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, strict: false, regexp: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON2)
{
    this.JSON = this.JSON2 = {};
}

(function () {
    "use strict";

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }

    function str(key, holder) {
        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];
        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
        case 'string':
            return quote(value);
        case 'number':
            return isFinite(value) ? String(value) : 'null';
        case 'boolean':
        case 'null':
            return String(value);
        case 'object':
            if (!value) {
                return 'null';
            }
            gap += indent;
            partial = [];
            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }
                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }
            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }
            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }
    if (typeof JSON2.stringify !== 'function') {
        JSON2.stringify = function (value, replacer, space) {
            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }
            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON2.stringify');
            }
            return str('', {'': value});
        };
    }
    if (typeof JSON2.parse !== 'function') {
        JSON2.parse = function (text, reviver) {
            var j;
            function walk(holder, key) {
                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }
            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                j = eval('(' + text + ')');
                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }
            throw new SyntaxError('JSON2.parse');
        };
    }
}());

/*! nanoScrollerJS - v0.8.7 - 2015
* http://jamesflorentino.github.com/nanoScrollerJS/
* Copyright (c) 2015 James Florentino; Licensed MIT */
(function(factory) {
  if (jQuery) {
    return factory(jQuery, window, document);
  }
  else if (typeof define === 'function' && define.amd) {
    return define(['jquery'], function($) {
      return factory($, window, document);
    });
  } else if (typeof exports === 'object') {
    return module.exports = factory(require('jquery'), window, document);
  }
})(function($, window, document) {
  "use strict";
  var BROWSER_IS_IE7, BROWSER_SCROLLBAR_WIDTH, DOMSCROLL, DOWN, DRAG, ENTER, KEYDOWN, KEYUP, MOUSEDOWN, MOUSEENTER, MOUSEMOVE, MOUSEUP, MOUSEWHEEL, NanoScroll, PANEDOWN, RESIZE, SCROLL, SCROLLBAR, TOUCHMOVE, UP, WHEEL, cAF, defaults, getBrowserScrollbarWidth, hasTransform, isFFWithBuggyScrollbar, rAF, transform, _elementStyle, _prefixStyle, _vendor;
  defaults = {

    /**
      a classname for the pane element.
      @property paneClass
      @type String
      @default 'nano-pane'
     */
    paneClass: 'nano-pane',

    /**
      a classname for the slider element.
      @property sliderClass
      @type String
      @default 'nano-slider'
     */
    sliderClass: 'nano-slider',

    /**
      a classname for the content element.
      @property contentClass
      @type String
      @default 'nano-content'
     */
    contentClass: 'nano-content',

    /**
      a classname for enabled mode
      @property enabledClass
      @type String
      @default 'has-scrollbar'
     */
    enabledClass: 'has-scrollbar',

    /**
      a classname for flashed mode
      @property flashedClass
      @type String
      @default 'flashed'
     */
    flashedClass: 'flashed',

    /**
      a classname for active mode
      @property activeClass
      @type String
      @default 'active'
     */
    activeClass: 'active',

    /**
      a setting to enable native scrolling in iOS devices.
      @property iOSNativeScrolling
      @type Boolean
      @default false
     */
    iOSNativeScrolling: false,

    /**
      a setting to prevent the rest of the page being
      scrolled when user scrolls the `.content` element.
      @property preventPageScrolling
      @type Boolean
      @default false
     */
    preventPageScrolling: false,

    /**
      a setting to disable binding to the resize event.
      @property disableResize
      @type Boolean
      @default false
     */
    disableResize: false,

    /**
      a setting to make the scrollbar always visible.
      @property alwaysVisible
      @type Boolean
      @default false
     */
    alwaysVisible: false,

    /**
      a default timeout for the `flash()` method.
      @property flashDelay
      @type Number
      @default 1500
     */
    flashDelay: 1500,

    /**
      a minimum height for the `.slider` element.
      @property sliderMinHeight
      @type Number
      @default 20
     */
    sliderMinHeight: 20,

    /**
      a maximum height for the `.slider` element.
      @property sliderMaxHeight
      @type Number
      @default null
     */
    sliderMaxHeight: null,

    /**
      an alternate document context.
      @property documentContext
      @type Document
      @default null
     */
    documentContext: null,

    /**
      an alternate window context.
      @property windowContext
      @type Window
      @default null
     */
    windowContext: null
  };

  /**
    @property SCROLLBAR
    @type String
    @static
    @final
    @private
   */
  SCROLLBAR = 'scrollbar';

  /**
    @property SCROLL
    @type String
    @static
    @final
    @private
   */
  SCROLL = 'scroll';

  /**
    @property MOUSEDOWN
    @type String
    @final
    @private
   */
  MOUSEDOWN = 'mousedown';

  /**
    @property MOUSEENTER
    @type String
    @final
    @private
   */
  MOUSEENTER = 'mouseenter';

  /**
    @property MOUSEMOVE
    @type String
    @static
    @final
    @private
   */
  MOUSEMOVE = 'mousemove';

  /**
    @property MOUSEWHEEL
    @type String
    @final
    @private
   */
  MOUSEWHEEL = 'mousewheel';

  /**
    @property MOUSEUP
    @type String
    @static
    @final
    @private
   */
  MOUSEUP = 'mouseup';

  /**
    @property RESIZE
    @type String
    @final
    @private
   */
  RESIZE = 'resize';

  /**
    @property DRAG
    @type String
    @static
    @final
    @private
   */
  DRAG = 'drag';

  /**
    @property ENTER
    @type String
    @static
    @final
    @private
   */
  ENTER = 'enter';

  /**
    @property UP
    @type String
    @static
    @final
    @private
   */
  UP = 'up';

  /**
    @property PANEDOWN
    @type String
    @static
    @final
    @private
   */
  PANEDOWN = 'panedown';

  /**
    @property DOMSCROLL
    @type String
    @static
    @final
    @private
   */
  DOMSCROLL = 'DOMMouseScroll';

  /**
    @property DOWN
    @type String
    @static
    @final
    @private
   */
  DOWN = 'down';

  /**
    @property WHEEL
    @type String
    @static
    @final
    @private
   */
  WHEEL = 'wheel';

  /**
    @property KEYDOWN
    @type String
    @static
    @final
    @private
   */
  KEYDOWN = 'keydown';

  /**
    @property KEYUP
    @type String
    @static
    @final
    @private
   */
  KEYUP = 'keyup';

  /**
    @property TOUCHMOVE
    @type String
    @static
    @final
    @private
   */
  TOUCHMOVE = 'touchmove';

  /**
    @property BROWSER_IS_IE7
    @type Boolean
    @static
    @final
    @private
   */
  BROWSER_IS_IE7 = window.navigator.appName === 'Microsoft Internet Explorer' && /msie 7./i.test(window.navigator.appVersion) && window.ActiveXObject;

  /**
    @property BROWSER_SCROLLBAR_WIDTH
    @type Number
    @static
    @default null
    @private
   */
  BROWSER_SCROLLBAR_WIDTH = null;
  rAF = window.requestAnimationFrame;
  cAF = window.cancelAnimationFrame;
  _elementStyle = document.createElement('div').style;
  _vendor = (function() {
    var i, transform, vendor, vendors, _i, _len;
    vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'];
    for (i = _i = 0, _len = vendors.length; _i < _len; i = ++_i) {
      vendor = vendors[i];
      transform = vendors[i] + 'ransform';
      if (transform in _elementStyle) {
        return vendors[i].substr(0, vendors[i].length - 1);
      }
    }
    return false;
  })();
  _prefixStyle = function(style) {
    if (_vendor === false) {
      return false;
    }
    if (_vendor === '') {
      return style;
    }
    return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
  };
  transform = _prefixStyle('transform');
  hasTransform = transform !== false;

  /**
    Returns browser's native scrollbar width
    @method getBrowserScrollbarWidth
    @return {Number} the scrollbar width in pixels
    @static
    @private
   */
  getBrowserScrollbarWidth = function() {
    var outer, outerStyle, scrollbarWidth;
    outer = document.createElement('div');
    outerStyle = outer.style;
    outerStyle.position = 'absolute';
    outerStyle.width = '100px';
    outerStyle.height = '100px';
    outerStyle.overflow = SCROLL;
    outerStyle.top = '-9999px';
    document.body.appendChild(outer);
    scrollbarWidth = outer.offsetWidth - outer.clientWidth;
    document.body.removeChild(outer);
    return scrollbarWidth;
  };
  isFFWithBuggyScrollbar = function() {
    var isOSXFF, ua, version;
    ua = window.navigator.userAgent;
    isOSXFF = /(?=.+Mac OS X)(?=.+Firefox)/.test(ua);
    if (!isOSXFF) {
      return false;
    }
    version = /Firefox\/\d{2}\./.exec(ua);
    if (version) {
      version = version[0].replace(/\D+/g, '');
    }
    return isOSXFF && +version > 23;
  };

  /**
    @class NanoScroll
    @param element {HTMLElement|Node} the main element
    @param options {Object} nanoScroller's options
    @constructor
   */
  NanoScroll = (function() {
    function NanoScroll(el, options) {
      this.el = el;
      this.options = options;
      BROWSER_SCROLLBAR_WIDTH || (BROWSER_SCROLLBAR_WIDTH = getBrowserScrollbarWidth());
      this.$el = $(this.el);
      this.doc = $(this.options.documentContext || document);
      this.win = $(this.options.windowContext || window);
      this.body = this.doc.find('body');
      this.$content = this.$el.children("." + this.options.contentClass);
      this.$content.attr('tabindex', this.options.tabIndex || 0);
      this.content = this.$content[0];
      this.previousPosition = 0;
      if (this.options.iOSNativeScrolling && (this.el.style.WebkitOverflowScrolling != null)) {
        this.nativeScrolling();
      } else {
        this.generate();
      }
      this.createEvents();
      this.addEvents();
      this.reset();
    }


    /**
      Prevents the rest of the page being scrolled
      when user scrolls the `.nano-content` element.
      @method preventScrolling
      @param event {Event}
      @param direction {String} Scroll direction (up or down)
      @private
     */

    NanoScroll.prototype.preventScrolling = function(e, direction) {
      if (!this.isActive) {
        return;
      }
      if (e.type === DOMSCROLL) {
        if (direction === DOWN && e.originalEvent.detail > 0 || direction === UP && e.originalEvent.detail < 0) {
          e.preventDefault();
        }
      } else if (e.type === MOUSEWHEEL) {
        if (!e.originalEvent || !e.originalEvent.wheelDelta) {
          return;
        }
        if (direction === DOWN && e.originalEvent.wheelDelta < 0 || direction === UP && e.originalEvent.wheelDelta > 0) {
          e.preventDefault();
        }
      }
    };


    /**
      Enable iOS native scrolling
      @method nativeScrolling
      @private
     */

    NanoScroll.prototype.nativeScrolling = function() {
      this.$content.css({
        WebkitOverflowScrolling: 'touch'
      });
      this.iOSNativeScrolling = true;
      this.isActive = true;
    };


    /**
      Updates those nanoScroller properties that
      are related to current scrollbar position.
      @method updateScrollValues
      @private
     */

    NanoScroll.prototype.updateScrollValues = function() {
      var content, direction;
      content = this.content;
      this.maxScrollTop = content.scrollHeight - content.clientHeight;
      this.prevScrollTop = this.contentScrollTop || 0;
      this.contentScrollTop = content.scrollTop;
      direction = this.contentScrollTop > this.previousPosition ? "down" : this.contentScrollTop < this.previousPosition ? "up" : "same";
      this.previousPosition = this.contentScrollTop;
      if (direction !== "same") {
        this.$el.trigger('update', {
          position: this.contentScrollTop,
          maximum: this.maxScrollTop,
          direction: direction
        });
      }
      if (!this.iOSNativeScrolling) {
        this.maxSliderTop = this.paneHeight - this.sliderHeight;
        this.sliderTop = this.maxScrollTop === 0 ? 0 : this.contentScrollTop * this.maxSliderTop / this.maxScrollTop;
      }
    };


    /**
      Updates CSS styles for current scroll position.
      Uses CSS 2d transfroms and `window.requestAnimationFrame` if available.
      @method setOnScrollStyles
      @private
     */

    NanoScroll.prototype.setOnScrollStyles = function() {
      var cssValue;
      if (hasTransform) {
        cssValue = {};
        cssValue[transform] = "translate(0, " + this.sliderTop + "px)";
      } else {
        cssValue = {
          top: this.sliderTop
        };
      }
      if (rAF) {
        if (cAF && this.scrollRAF) {
          cAF(this.scrollRAF);
        }
        this.scrollRAF = rAF((function(_this) {
          return function() {
            _this.scrollRAF = null;
            return _this.slider.css(cssValue);
          };
        })(this));
      } else {
        this.slider.css(cssValue);
      }
    };


    /**
      Creates event related methods
      @method createEvents
      @private
     */

    NanoScroll.prototype.createEvents = function() {
      this.events = {
        down: (function(_this) {
          return function(e) {
            _this.isBeingDragged = true;
            _this.offsetY = e.pageY - _this.slider.offset().top;
            if (!_this.slider.is(e.target)) {
              _this.offsetY = 0;
            }
            _this.pane.addClass(_this.options.activeClass);
            _this.doc.bind(MOUSEMOVE, _this.events[DRAG]).bind(MOUSEUP, _this.events[UP]);
            _this.body.bind(MOUSEENTER, _this.events[ENTER]);
            return false;
          };
        })(this),
        drag: (function(_this) {
          return function(e) {
            _this.sliderY = e.pageY - _this.$el.offset().top - _this.paneTop - (_this.offsetY || _this.sliderHeight * 0.5);
            _this.scroll();
            if (_this.contentScrollTop >= _this.maxScrollTop && _this.prevScrollTop !== _this.maxScrollTop) {
              _this.$el.trigger('scrollend');
            } else if (_this.contentScrollTop === 0 && _this.prevScrollTop !== 0) {
              _this.$el.trigger('scrolltop');
            }
            return false;
          };
        })(this),
        up: (function(_this) {
          return function(e) {
            _this.isBeingDragged = false;
            _this.pane.removeClass(_this.options.activeClass);
            _this.doc.unbind(MOUSEMOVE, _this.events[DRAG]).unbind(MOUSEUP, _this.events[UP]);
            _this.body.unbind(MOUSEENTER, _this.events[ENTER]);
            return false;
          };
        })(this),
        resize: (function(_this) {
          return function(e) {
            _this.reset();
          };
        })(this),
        panedown: (function(_this) {
          return function(e) {
            _this.sliderY = (e.offsetY || e.originalEvent.layerY) - (_this.sliderHeight * 0.5);
            _this.scroll();
            _this.events.down(e);
            return false;
          };
        })(this),
        scroll: (function(_this) {
          return function(e) {
            _this.updateScrollValues();
            if (_this.isBeingDragged) {
              return;
            }
            if (!_this.iOSNativeScrolling) {
              _this.sliderY = _this.sliderTop;
              _this.setOnScrollStyles();
            }
            if (e == null) {
              return;
            }
            if (_this.contentScrollTop >= _this.maxScrollTop) {
              if (_this.options.preventPageScrolling) {
                _this.preventScrolling(e, DOWN);
              }
              if (_this.prevScrollTop !== _this.maxScrollTop) {
                _this.$el.trigger('scrollend');
              }
            } else if (_this.contentScrollTop === 0) {
              if (_this.options.preventPageScrolling) {
                _this.preventScrolling(e, UP);
              }
              if (_this.prevScrollTop !== 0) {
                _this.$el.trigger('scrolltop');
              }
            }
          };
        })(this),
        wheel: (function(_this) {
          return function(e) {
            var delta;
            if (e == null) {
              return;
            }
            delta = e.delta || e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail || (e.originalEvent && -e.originalEvent.detail);
            if (delta) {
              _this.sliderY += -delta / 3;
            }
            _this.scroll();
            return false;
          };
        })(this),
        enter: (function(_this) {
          return function(e) {
            var _ref;
            if (!_this.isBeingDragged) {
              return;
            }
            if ((e.buttons || e.which) !== 1) {
              return (_ref = _this.events)[UP].apply(_ref, arguments);
            }
          };
        })(this)
      };
    };


    /**
      Adds event listeners with jQuery.
      @method addEvents
      @private
     */

    NanoScroll.prototype.addEvents = function() {
      var events;
      this.removeEvents();
      events = this.events;
      if (!this.options.disableResize) {
        this.win.bind(RESIZE, events[RESIZE]);
      }
      if (!this.iOSNativeScrolling) {
        this.slider.bind(MOUSEDOWN, events[DOWN]);
        this.pane.bind(MOUSEDOWN, events[PANEDOWN]).bind("" + MOUSEWHEEL + " " + DOMSCROLL, events[WHEEL]);
      }
      this.$content.bind("" + SCROLL + " " + MOUSEWHEEL + " " + DOMSCROLL + " " + TOUCHMOVE, events[SCROLL]);
    };


    /**
      Removes event listeners with jQuery.
      @method removeEvents
      @private
     */

    NanoScroll.prototype.removeEvents = function() {
      var events;
      events = this.events;
      this.win.unbind(RESIZE, events[RESIZE]);
      if (!this.iOSNativeScrolling) {
        this.slider.unbind();
        this.pane.unbind();
      }
      this.$content.unbind("" + SCROLL + " " + MOUSEWHEEL + " " + DOMSCROLL + " " + TOUCHMOVE, events[SCROLL]);
    };


    /**
      Generates nanoScroller's scrollbar and elements for it.
      @method generate
      @chainable
      @private
     */

    NanoScroll.prototype.generate = function() {
      var contentClass, cssRule, currentPadding, options, pane, paneClass, sliderClass;
      options = this.options;
      paneClass = options.paneClass, sliderClass = options.sliderClass, contentClass = options.contentClass;
      if (!(pane = this.$el.children("." + paneClass)).length && !pane.children("." + sliderClass).length) {
        this.$el.append("<div class=\"" + paneClass + "\"><div class=\"" + sliderClass + "\" /></div>");
      }
      this.pane = this.$el.children("." + paneClass);
      this.slider = this.pane.find("." + sliderClass);
      if (BROWSER_SCROLLBAR_WIDTH === 0 && isFFWithBuggyScrollbar()) {
        currentPadding = window.getComputedStyle(this.content, null).getPropertyValue('padding-right').replace(/[^0-9.]+/g, '');
        cssRule = {
          right: -14,
          paddingRight: +currentPadding + 14
        };
      } else if (BROWSER_SCROLLBAR_WIDTH) {
        cssRule = {
          right: -BROWSER_SCROLLBAR_WIDTH
        };
        this.$el.addClass(options.enabledClass);
      }
      if (cssRule != null) {
        this.$content.css(cssRule);
      }
      return this;
    };


    /**
      @method restore
      @private
     */

    NanoScroll.prototype.restore = function() {
      this.stopped = false;
      if (!this.iOSNativeScrolling) {
        this.pane.show();
      }
      this.addEvents();
    };


    /**
      Resets nanoScroller's scrollbar.
      @method reset
      @chainable
      @example
          $(".nano").nanoScroller();
     */

    NanoScroll.prototype.reset = function() {
      var content, contentHeight, contentPosition, contentStyle, contentStyleOverflowY, paneBottom, paneHeight, paneOuterHeight, paneTop, parentMaxHeight, right, sliderHeight;
      if (this.iOSNativeScrolling) {
        this.contentHeight = this.content.scrollHeight;
        return;
      }
      if (!this.$el.find("." + this.options.paneClass).length) {
        this.generate().stop();
      }
      if (this.stopped) {
        this.restore();
      }
      content = this.content;
      contentStyle = content.style;
      contentStyleOverflowY = contentStyle.overflowY;
      if (BROWSER_IS_IE7) {
        this.$content.css({
          height: this.$content.height()
        });
      }
      contentHeight = content.scrollHeight + BROWSER_SCROLLBAR_WIDTH;
      parentMaxHeight = parseInt(this.$el.css("max-height"), 10);
      if (parentMaxHeight > 0) {
        this.$el.height("");
        this.$el.height(content.scrollHeight > parentMaxHeight ? parentMaxHeight : content.scrollHeight);
      }
      paneHeight = this.pane.outerHeight(false);
      paneTop = parseInt(this.pane.css('top'), 10);
      paneBottom = parseInt(this.pane.css('bottom'), 10);
      paneOuterHeight = paneHeight + paneTop + paneBottom;
      sliderHeight = Math.round(paneOuterHeight / contentHeight * paneHeight);
      if (sliderHeight < this.options.sliderMinHeight) {
        sliderHeight = this.options.sliderMinHeight;
      } else if ((this.options.sliderMaxHeight != null) && sliderHeight > this.options.sliderMaxHeight) {
        sliderHeight = this.options.sliderMaxHeight;
      }
      if (contentStyleOverflowY === SCROLL && contentStyle.overflowX !== SCROLL) {
        sliderHeight += BROWSER_SCROLLBAR_WIDTH;
      }
      this.maxSliderTop = paneOuterHeight - sliderHeight;
      this.contentHeight = contentHeight;
      this.paneHeight = paneHeight;
      this.paneOuterHeight = paneOuterHeight;
      this.sliderHeight = sliderHeight;
      this.paneTop = paneTop;
      this.slider.height(sliderHeight);
      this.events.scroll();
      this.pane.show();
      this.isActive = true;
      if ((content.scrollHeight === content.clientHeight) || (this.pane.outerHeight(true) >= content.scrollHeight && contentStyleOverflowY !== SCROLL)) {
        this.pane.hide();
        this.isActive = false;
      } else if (this.el.clientHeight === content.scrollHeight && contentStyleOverflowY === SCROLL) {
        this.slider.hide();
      } else {
        this.slider.show();
      }
      this.pane.css({
        opacity: (this.options.alwaysVisible ? 1 : ''),
        visibility: (this.options.alwaysVisible ? 'visible' : '')
      });
      contentPosition = this.$content.css('position');
      if (contentPosition === 'static' || contentPosition === 'relative') {
        right = parseInt(this.$content.css('right'), 10);
        if (right) {
          this.$content.css({
            right: '',
            marginRight: right
          });
        }
      }
      return this;
    };


    /**
      @method scroll
      @private
      @example
          $(".nano").nanoScroller({ scroll: 'top' });
     */

    NanoScroll.prototype.scroll = function() {
      if (!this.isActive) {
        return;
      }
      this.sliderY = Math.max(0, this.sliderY);
      this.sliderY = Math.min(this.maxSliderTop, this.sliderY);
      this.$content.scrollTop(this.maxScrollTop * this.sliderY / this.maxSliderTop);
      if (!this.iOSNativeScrolling) {
        this.updateScrollValues();
        this.setOnScrollStyles();
      }
      return this;
    };


    /**
      Scroll at the bottom with an offset value
      @method scrollBottom
      @param offsetY {Number}
      @chainable
      @example
          $(".nano").nanoScroller({ scrollBottom: value });
     */

    NanoScroll.prototype.scrollBottom = function(offsetY) {
      if (!this.isActive) {
        return;
      }
      this.$content.scrollTop(this.contentHeight - this.$content.height() - offsetY).trigger(MOUSEWHEEL);
      this.stop().restore();
      return this;
    };


    /**
      Scroll at the top with an offset value
      @method scrollTop
      @param offsetY {Number}
      @chainable
      @example
          $(".nano").nanoScroller({ scrollTop: value });
     */

    NanoScroll.prototype.scrollTop = function(offsetY) {
      if (!this.isActive) {
        return;
      }
      this.$content.scrollTop(+offsetY).trigger(MOUSEWHEEL);
      this.stop().restore();
      return this;
    };


    /**
      Scroll to an element
      @method scrollTo
      @param node {Node} A node to scroll to.
      @chainable
      @example
          $(".nano").nanoScroller({ scrollTo: $('#a_node') });
     */

    NanoScroll.prototype.scrollTo = function(node) {
      if (!this.isActive) {
        return;
      }
      this.scrollTop(this.$el.find(node).get(0).offsetTop);
      return this;
    };


    /**
      To stop the operation.
      This option will tell the plugin to disable all event bindings and hide the gadget scrollbar from the UI.
      @method stop
      @chainable
      @example
          $(".nano").nanoScroller({ stop: true });
     */

    NanoScroll.prototype.stop = function() {
      if (cAF && this.scrollRAF) {
        cAF(this.scrollRAF);
        this.scrollRAF = null;
      }
      this.stopped = true;
      this.removeEvents();
      if (!this.iOSNativeScrolling) {
        this.pane.hide();
      }
      return this;
    };


    /**
      Destroys nanoScroller and restores browser's native scrollbar.
      @method destroy
      @chainable
      @example
          $(".nano").nanoScroller({ destroy: true });
     */

    NanoScroll.prototype.destroy = function() {
      if (!this.stopped) {
        this.stop();
      }
      if (!this.iOSNativeScrolling && this.pane.length) {
        this.pane.remove();
      }
      if (BROWSER_IS_IE7) {
        this.$content.height('');
      }
      this.$content.removeAttr('tabindex');
      if (this.$el.hasClass(this.options.enabledClass)) {
        this.$el.removeClass(this.options.enabledClass);
        this.$content.css({
          right: ''
        });
      }
      return this;
    };


    /**
      To flash the scrollbar gadget for an amount of time defined in plugin settings (defaults to 1,5s).
      Useful if you want to show the user (e.g. on pageload) that there is more content waiting for him.
      @method flash
      @chainable
      @example
          $(".nano").nanoScroller({ flash: true });
     */

    NanoScroll.prototype.flash = function() {
      if (this.iOSNativeScrolling) {
        return;
      }
      if (!this.isActive) {
        return;
      }
      this.reset();
      this.pane.addClass(this.options.flashedClass);
      setTimeout((function(_this) {
        return function() {
          _this.pane.removeClass(_this.options.flashedClass);
        };
      })(this), this.options.flashDelay);
      return this;
    };

    return NanoScroll;

  })();
  $.fn.nanoScroller = function(settings) {
    return this.each(function() {
      var options, scrollbar;
      if (!(scrollbar = this.nanoscroller)) {
        options = $.extend({}, defaults, settings);
        this.nanoscroller = scrollbar = new NanoScroll(this, options);
      }
      if (settings && typeof settings === "object") {
        $.extend(scrollbar.options, settings);
        if (settings.scrollBottom != null) {
          return scrollbar.scrollBottom(settings.scrollBottom);
        }
        if (settings.scrollTop != null) {
          return scrollbar.scrollTop(settings.scrollTop);
        }
        if (settings.scrollTo) {
          return scrollbar.scrollTo(settings.scrollTo);
        }
        if (settings.scroll === 'bottom') {
          return scrollbar.scrollBottom(0);
        }
        if (settings.scroll === 'top') {
          return scrollbar.scrollTop(0);
        }
        if (settings.scroll && settings.scroll instanceof $) {
          return scrollbar.scrollTo(settings.scroll);
        }
        if (settings.stop) {
          return scrollbar.stop();
        }
        if (settings.destroy) {
          return scrollbar.destroy();
        }
        if (settings.flash) {
          return scrollbar.flash();
        }
      }
      return scrollbar.reset();
    });
  };
  $.fn.nanoScroller.Constructor = NanoScroll;
});

//# sourceMappingURL=jquery.nanoscroller.js.map

/*
 * jQuery Autocomplete plugin 1.1
 * 
 * Copyright (c) 2009 Jörn Zaefferer
 * 
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */

;
(function($) {

	$.fn.extend({
				autocomplete : function(urlOrData, options) {
					var isUrl = typeof urlOrData == "string";
					options = $.extend({}, $.Autocompleter.defaults, {
								url : isUrl ? urlOrData : null,
								data : isUrl ? null : urlOrData,
								delay : isUrl
										? $.Autocompleter.defaults.delay
										: 10,
								max : options && !options.scroll ? 10 : 150
							}, options);

					// if highlight is set to false, replace it with a
					// do-nothing function
					options.highlight = options.highlight || function(value) {
						return value;
					};

					// if the formatMatch option is not specified, then use
					// formatItem for backwards compatibility
					options.formatMatch = options.formatMatch
							|| options.formatItem;

					return this.each(function() {
								new $.Autocompleter(this, options);
							});
				},
				result : function(handler) {
					return this.bind("result", handler);
				},
				search : function(handler) {
					return this.trigger("search", [handler]);
				},
				flushCache : function() {
					return this.trigger("flushCache");
				},
				setOptions : function(options) {
					return this.trigger("setOptions", [options]);
				},
				unautocomplete : function() {
					return this.trigger("unautocomplete");
				}
			});

	$.Autocompleter = function(input, options) {

		var KEY = {
			UP : 38,
			DOWN : 40,
			DEL : 46,
			TAB : 9,
			RETURN : 13,
			ESC : 27,
			COMMA : 188,
			PAGEUP : 33,
			PAGEDOWN : 34,
			BACKSPACE : 8
		};

		// Create $ object for input element
		var $input = $(input).attr("autocomplete", "off")
				.addClass(options.inputClass);

		var timeout;
		var previousValue = "";
		var cache = $.Autocompleter.Cache(options);
		var hasFocus = 0;
		var lastKeyPressCode;
		var config = {
			mouseDownOnSelect : false
		};
		var select = $.Autocompleter.Select(options, input, selectCurrent,
				config);

		var blockSubmit;

		// prevent form submit in opera when selecting with return key
		$.browser.opera
				&& $(input.form).bind("submit.autocomplete", function() {
							if (blockSubmit) {
								blockSubmit = false;
								return false;
							}
						});

		// only opera doesn't trigger keydown multiple times while pressed,
		// others don't work with keypress at all
		$input.bind(($.browser.opera ? "keypress" : "keyup") + ".autocomplete",
				function(event) {
					// a keypress means the input has focus
					// avoids issue where input had focus before the
					// autocomplete was applied
					hasFocus = 1;
					// track last key pressed
					lastKeyPressCode = event.keyCode;
					switch (event.keyCode) {

						case KEY.UP :
							event.preventDefault();
							if (select.visible()) {
								select.prev();
							} else {
								onChange(0, true);
							}
							break;

						case KEY.DOWN :
							event.preventDefault();
							if (select.visible()) {
								select.next();
							} else {
								onChange(0, true);
							}
							break;

						case KEY.PAGEUP :
							event.preventDefault();
							if (select.visible()) {
								select.pageUp();
							} else {
								onChange(0, true);
							}
							break;

						case KEY.PAGEDOWN :
							event.preventDefault();
							if (select.visible()) {
								select.pageDown();
							} else {
								onChange(0, true);
							}
							break;

						// matches also semicolon
						case options.multiple
								&& $.trim(options.multipleSeparator) == ","
								&& KEY.COMMA :
						case KEY.TAB :
						case KEY.RETURN :
							if (selectCurrent()) {
								// stop default to prevent a form submit, Opera
								// needs special handling
								event.preventDefault();
								blockSubmit = true;
								return false;
							}
							break;

						case KEY.ESC :
							select.hide();
							break;

						default :
							clearTimeout(timeout);
							timeout = setTimeout(onChange, options.delay);
							break;
					}
				}).focus(function() {
					// track whether the field has focus, we shouldn't process
					// any
					// results if the field no longer has focus
					hasFocus++;
				}).blur(function() {
					hasFocus = 0;
					if (!config.mouseDownOnSelect) {
						hideResults();
					}
				}).click(function() {
					// show select when clicking in a focused field
					if (hasFocus++ > 1 && !select.visible()) {
						onChange(0, true);
					}
				}).bind("search", function() {
			// TODO why not just specifying both arguments?
			var fn = (arguments.length > 1) ? arguments[1] : null;
			function findValueCallback(q, data) {
				var result;
				if (data && data.length) {
					for (var i = 0; i < data.length; i++) {
						if (data[i].result.toLowerCase() == q.toLowerCase()) {
							result = data[i];
							break;
						}
					}
				}
				if (typeof fn == "function")
					fn(result);
				else
					$input.trigger("result", result
									&& [result.data, result.value]);
			}
			$.each(trimWords($input.val()), function(i, value) {
						request(value, findValueCallback, findValueCallback);
					});
		}).bind("flushCache", function() {
					cache.flush();
				}).bind("setOptions", function() {
					$.extend(options, arguments[1]);
					// if we've updated the data, repopulate
					if ("data" in arguments[1])
						cache.populate();
				}).bind("unautocomplete", function() {
					select.unbind();
					$input.unbind();
					$(input.form).unbind(".autocomplete");
				}).bind("input", function() {
					// 支持firefox对中文的输入
					onChange(0, true);
				});

		function selectCurrent() {
			var selected = select.selected();
			if (!selected)
				return false;

			var v = selected.result;
			previousValue = v;

			if (options.multiple) {
				var words = trimWords($input.val());
				if (words.length > 1) {
					var seperator = options.multipleSeparator.length;
					var cursorAt = $(input).selection().start;
					var wordAt, progress = 0;
					$.each(words, function(i, word) {
								progress += word.length;
								if (cursorAt <= progress) {
									wordAt = i;
									return false;
								}
								progress += seperator;
							});
					words[wordAt] = v;
					// TODO this should set the cursor to the right position,
					// but it gets overriden somewhere
					// $.Autocompleter.Selection(input, progress + seperator,
					// progress + seperator);
					v = words.join(options.multipleSeparator);
				}
				v += options.multipleSeparator;
			}

			$input.val(v);
			hideResultsNow();
			$input.trigger("result", [selected.data, selected.value]);
			return true;
		}

		function onChange(crap, skipPrevCheck) {
			if (lastKeyPressCode == KEY.DEL) {
				select.hide();
				return;
			}

			var currentValue = $input.val();

			if (!skipPrevCheck && currentValue == previousValue)
				return;

			previousValue = currentValue;

			currentValue = lastWord(currentValue);
			if (currentValue.length >= options.minChars) {
				$input.addClass(options.loadingClass);
				if (!options.matchCase)
					currentValue = currentValue.toLowerCase();
				request(currentValue, receiveData, hideResultsNow);
			} else {
				stopLoading();
				select.hide();
			}
		};

		function trimWords(value) {
			if (!value)
				return [""];
			if (!options.multiple)
				return [$.trim(value)];
			return $.map(value.split(options.multipleSeparator),
					function(word) {
						return $.trim(value).length ? $.trim(word) : null;
					});
		}

		function lastWord(value) {
			if (!options.multiple)
				return value;
			var words = trimWords(value);
			if (words.length == 1)
				return words[0];
			var cursorAt = $(input).selection().start;
			if (cursorAt == value.length) {
				words = trimWords(value)
			} else {
				words = trimWords(value.replace(value.substring(cursorAt), ""));
			}
			return words[words.length - 1];
		}

		// fills in the input box w/the first match (assumed to be the best
		// match)
		// q: the term entered
		// sValue: the first matching result
		function autoFill(q, sValue) {
			// autofill in the complete box w/the first match as long as the
			// user hasn't entered in more data
			// if the last user key pressed was backspace, don't autofill
			if (options.autoFill
					&& (lastWord($input.val()).toLowerCase() == q.toLowerCase())
					&& lastKeyPressCode != KEY.BACKSPACE) {
				// fill in the value (keep the case the user has typed)
				$input.val($input.val()
						+ sValue.substring(lastWord(previousValue).length));
				// select the portion of the value not typed by the user (so the
				// next character will erase)
				$(input).selection(previousValue.length,
						previousValue.length + sValue.length);
			}
		};

		function hideResults() {
			clearTimeout(timeout);
			timeout = setTimeout(hideResultsNow, 200);
		};

		function hideResultsNow() {
			var wasVisible = select.visible();
			select.hide();
			clearTimeout(timeout);
			stopLoading();
			if (options.mustMatch) {
				// call search and run callback
				$input.search(function(result) {
							// if no value found, clear the input box
							if (!result) {
								if (options.multiple) {
									var words = trimWords($input.val()).slice(
											0, -1);
									$input.val(words
											.join(options.multipleSeparator)
											+ (words.length
													? options.multipleSeparator
													: ""));
								} else {
									$input.val("");
									$input.trigger("result", null);
								}
							}
						});
			}
		};

		function receiveData(q, data) {
			if (data && data.length && hasFocus) {
				stopLoading();
				select.display(data, q);
				autoFill(q, data[0].value);
				select.show();
			} else {
				hideResultsNow();
			}
		};

		function request(term, success, failure) {
			if (!options.matchCase)
				term = term.toLowerCase();
			var data = cache.load(term);
			// recieve the cached data
			if (data && data.length) {
				success(term, data);
				// if an AJAX url has been supplied, try loading the data now
			} else if ((typeof options.url == "string")
					&& (options.url.length > 0)) {

				var extraParams = {
					timestamp : +new Date()
				};
				$.each(options.extraParams, function(key, param) {
							extraParams[key] = typeof param == "function"
									? param()
									: param;
						});

				$.ajax({
							// try to leverage ajaxQueue plugin to abort
							// previous requests
							type : "POST",// 不加此项,默认则为get
							mode : "abort",
							// limit abortion to this input
							port : "autocomplete" + input.name,
							dataType : options.dataType,
							url : options.url,
							data : $.extend({
										q : lastWord(term),
										limit : options.max
									}, extraParams),
							success : function(data) {// 回调函数
								
								var parsed = options.parse
										&& options.parse(data) || parse(data);
								cache.add(term, parsed);
								success(term, parsed);
							}
						});
			} else {
				// if we have a failure, we need to empty the list -- this
				// prevents the the [TAB] key from selecting the last successful
				// match
				select.emptyList();
				failure(term);
			}
		};

		function parse(data) {
			var parsed = [];
			var rows = data.split("\n");
			for (var i = 0; i < rows.length; i++) {
				var row = $.trim(rows[i]);
				if (row) {
					row = row.split("|");
					parsed[parsed.length] = {
						data : row,
						value : row[0],
						result : options.formatResult
								&& options.formatResult(row, row[0]) || row[0]
					};
				}
			}
			return parsed;
		};

		function stopLoading() {
			$input.removeClass(options.loadingClass);
		};

	};

	$.Autocompleter.defaults = {
		inputClass : "ac_input",
		resultsClass : "ac_results",
		loadingClass : "ac_loading",
		minChars : 1,
		delay : 400,
		matchCase : false,
		matchSubset : true,
		matchContains : false,
		cacheLength : 10,
		max : 100,
		mustMatch : false,
		extraParams : {},
		selectFirst : true,
		formatItem : function(row) {
			return row[0];
		},
		formatMatch : null,
		autoFill : false,
		width : 0,
		multiple : false,
		multipleSeparator : ", ",
		highlight : function(value, term) {
			return value
					.replace(
							new RegExp(
									"(?![^&;]+;)(?!<[^<>]*)("
											+ term
													.replace(
															/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,
															"\\$1")
											+ ")(?![^<>]*>)(?![^&;]+;)", "gi"),
							"<strong>$1</strong>");
		},
		scroll : true,
		scrollHeight : 180
	};

	$.Autocompleter.Cache = function(options) {

		var data = {};
		var length = 0;

		function matchSubset(s, sub) {
			if (!options.matchCase)
				s = s.toLowerCase();
			var i = s.indexOf(sub);
			if (options.matchContains == "word") {
				i = s.toLowerCase().search("\\b" + sub.toLowerCase());
			}
			if (i == -1)
				return false;
			return i == 0 || options.matchContains;
		};

		function add(q, value) {
			if (length > options.cacheLength) {
				flush();
			}
			if (!data[q]) {
				length++;
			}
			data[q] = value;
		}

		function populate() {
			if (!options.data)
				return false;
			// track the matches
			var stMatchSets = {}, nullData = 0;

			// no url was specified, we need to adjust the cache length to make
			// sure it fits the local data store
			if (!options.url)
				options.cacheLength = 1;

			// track all options for minChars = 0
			stMatchSets[""] = [];

			// loop through the array and create a lookup structure
			for (var i = 0, ol = options.data.length; i < ol; i++) {
				var rawValue = options.data[i];
				// if rawValue is a string, make an array otherwise just
				// reference the array
				rawValue = (typeof rawValue == "string")
						? [rawValue]
						: rawValue;

				var value = options.formatMatch(rawValue, i + 1,
						options.data.length);
				if (value === false)
					continue;

				var firstChar = value.charAt(0).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if (!stMatchSets[firstChar])
					stMatchSets[firstChar] = [];

				// if the match is a string
				var row = {
					value : value,
					data : rawValue,
					result : options.formatResult
							&& options.formatResult(rawValue) || value
				};

				// push the current match into the set list
				stMatchSets[firstChar].push(row);

				// keep track of minChars zero items
				if (nullData++ < options.max) {
					stMatchSets[""].push(row);
				}
			};

			// add the data items to the cache
			$.each(stMatchSets, function(i, value) {
						// increase the cache size
						options.cacheLength++;
						// add to the cache
						add(i, value);
					});
		}

		// populate any existing data
		setTimeout(populate, 25);

		function flush() {
			data = {};
			length = 0;
		}

		return {
			flush : flush,
			add : add,
			populate : populate,
			load : function(q) {
				if (!options.cacheLength || !length)
					return null;
				/*
				 * if dealing w/local data and matchContains than we must make
				 * sure to loop through all the data collections looking for
				 * matches
				 */
				if (!options.url && options.matchContains) {
					// track all matches
					var csub = [];
					// loop through all the data grids for matches
					for (var k in data) {
						// don't search through the stMatchSets[""] (minChars:
						// 0) cache
						// this prevents duplicates
						if (k.length > 0) {
							var c = data[k];
							$.each(c, function(i, x) {
										// if we've got a match, add it to the
										// array
										if (matchSubset(x.value, q)) {
											csub.push(x);
										}
									});
						}
					}
					return csub;
				} else
				// if the exact item exists, use it
				if (data[q]) {
					return data[q];
				} else if (options.matchSubset) {
					for (var i = q.length - 1; i >= options.minChars; i--) {
						var c = data[q.substr(0, i)];
						if (c) {
							var csub = [];
							$.each(c, function(i, x) {
										if (matchSubset(x.value, q)) {
											csub[csub.length] = x;
										}
									});
							return csub;
						}
					}
				}
				return null;
			}
		};
	};

	$.Autocompleter.Select = function(options, input, select, config) {
		var CLASSES = {
			ACTIVE : "ac_over"
		};

		var listItems, active = -1, data, term = "", needsInit = true, element, list;

		// Create results
		function init() {
			if (!needsInit)
				return;
			element = $("<div/>").hide().addClass(options.resultsClass).css(
					"position", "absolute").appendTo(document.body);

			list = $("<ul/>").appendTo(element).mouseover(function(event) {
				if (target(event).nodeName
						&& target(event).nodeName.toUpperCase() == 'LI') {
					active = $("li", list).removeClass(CLASSES.ACTIVE)
							.index(target(event));
					$(target(event)).addClass(CLASSES.ACTIVE);
				}
			}).click(function(event) {
						$(target(event)).addClass(CLASSES.ACTIVE);
						select();
						// TODO provide option to avoid setting focus again
						// after selection? useful for cleanup-on-focus
						input.focus();
						return false;
					}).mousedown(function() {
						config.mouseDownOnSelect = true;
					}).mouseup(function() {
						config.mouseDownOnSelect = false;
					});

			if (options.width > 0)
				element.css("width", options.width);

			needsInit = false;
		}

		function target(event) {
			var element = event.target;
			while (element && element.tagName != "LI")
				element = element.parentNode;
			// more fun with IE, sometimes event.target is empty, just ignore it
			// then
			if (!element)
				return [];
			return element;
		}

		function moveSelect(step) {
			listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
			movePosition(step);
			var activeItem = listItems.slice(active, active + 1)
					.addClass(CLASSES.ACTIVE);
			if (options.scroll) {
				var offset = 0;
				listItems.slice(0, active).each(function() {
							offset += this.offsetHeight;
						});
				if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
					list.scrollTop(offset + activeItem[0].offsetHeight
							- list.innerHeight());
				} else if (offset < list.scrollTop()) {
					list.scrollTop(offset);
				}
			}
		};

		function movePosition(step) {
			active += step;
			if (active < 0) {
				active = listItems.size() - 1;
			} else if (active >= listItems.size()) {
				active = 0;
			}
		}

		function limitNumberOfItems(available) {
			return options.max && options.max < available
					? options.max
					: available;
		}

		function fillList() {
			list.empty();
			var max = limitNumberOfItems(data.length);
			for (var i = 0; i < max; i++) {
				if (!data[i])
					continue;
				var formatted = options.formatItem(data[i].data, i + 1, max,
						data[i].value, term);
				if (formatted === false)
					continue;
				var li = $("<li/>").html(options.highlight(formatted, term))
						.addClass(i % 2 == 0 ? "ac_even" : "ac_odd")
						.appendTo(list)[0];
				$.data(li, "ac_data", data[i]);
			}
			listItems = list.find("li");
			if (options.selectFirst) {
				listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
				active = 0;
			}
			// apply bgiframe if available
			if ($.fn.bgiframe)
				list.bgiframe();
		}

		return {
			display : function(d, q) {
				init();
				data = d;
				term = q;
				fillList();
			},
			next : function() {
				moveSelect(1);
			},
			prev : function() {
				moveSelect(-1);
			},
			pageUp : function() {
				if (active != 0 && active - 8 < 0) {
					moveSelect(-active);
				} else {
					moveSelect(-8);
				}
			},
			pageDown : function() {
				if (active != listItems.size() - 1
						&& active + 8 > listItems.size()) {
					moveSelect(listItems.size() - 1 - active);
				} else {
					moveSelect(8);
				}
			},
			hide : function() {
				element && element.hide();
				listItems && listItems.removeClass(CLASSES.ACTIVE);
				active = -1;
			},
			visible : function() {
				return element && element.is(":visible");
			},
			current : function() {
				return this.visible()
						&& (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst
								&& listItems[0]);
			},
			show : function() {
				var offset = $(input).offset();
				element.css({
					width : typeof options.width == "string"
							|| options.width > 0 ? options.width : $(input)
							.width(),
					top : offset.top + input.offsetHeight,
					left : offset.left
				}).show();
				if (options.scroll) {
					list.scrollTop(0);
					list.css({
								maxHeight : options.scrollHeight,
								overflow : 'auto'
							});

					if ($.browser.msie
							&& typeof document.body.style.maxHeight === "undefined") {
						var listHeight = 0;
						listItems.each(function() {
									listHeight += this.offsetHeight;
								});
						var scrollbarsVisible = listHeight > options.scrollHeight;
						list.css('height', scrollbarsVisible
										? options.scrollHeight
										: listHeight);
						if (!scrollbarsVisible) {
							// IE doesn't recalculate width when scrollbar
							// disappears
							listItems.width(list.width()
									- parseInt(listItems.css("padding-left"))
									- parseInt(listItems.css("padding-right")));
						}
					}

				}
			},
			selected : function() {
				var selected = listItems
						&& listItems.filter("." + CLASSES.ACTIVE)
								.removeClass(CLASSES.ACTIVE);
				return selected && selected.length
						&& $.data(selected[0], "ac_data");
			},
			emptyList : function() {
				list && list.empty();
			},
			unbind : function() {
				element && element.remove();
			}
		};
	};

	$.fn.selection = function(start, end) {
		if (start !== undefined) {
			return this.each(function() {
						if (this.createTextRange) {
							var selRange = this.createTextRange();
							if (end === undefined || start == end) {
								selRange.move("character", start);
								selRange.select();
							} else {
								selRange.collapse(true);
								selRange.moveStart("character", start);
								selRange.moveEnd("character", end);
								selRange.select();
							}
						} else if (this.setSelectionRange) {
							this.setSelectionRange(start, end);
						} else if (this.selectionStart) {
							this.selectionStart = start;
							this.selectionEnd = end;
						}
					});
		}
		var field = this[0];
		if (field.createTextRange) {
			var range = document.selection.createRange(), orig = field.value, teststring = "<->", textLength = range.text.length;
			range.text = teststring;
			var caretAt = field.value.indexOf(teststring);
			field.value = orig;
			this.selection(caretAt, caretAt + textLength);
			return {
				start : caretAt,
				end : caretAt + textLength
			}
		} else if (field.selectionStart !== undefined) {
			return {
				start : field.selectionStart,
				end : field.selectionEnd
			}
		}
	};

})(jQuery);
!function(t){t.extend(t.fn,{validate:function(e){if(!this.length)return void(e&&e.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing"));var i=t.data(this[0],"validator");return i?i:(i=new t.validator(e,this[0]),t.data(this[0],"validator",i),i.settings.onsubmit&&(this.find("input, button").filter(".cancel").click(function(){i.cancelSubmit=!0}),i.settings.submitHandler&&this.find("input, button").filter(":submit").click(function(){i.submitButton=this}),this.submit(function(e){function s(){if(i.settings.submitHandler){if(i.submitButton)var e=t("<input type='hidden'/>").attr("name",i.submitButton.name).val(i.submitButton.value).appendTo(i.currentForm);return i.settings.submitHandler.call(i,i.currentForm),i.submitButton&&e.remove(),!1}return!0}return i.settings.debug&&e.preventDefault(),i.cancelSubmit?(i.cancelSubmit=!1,s()):i.form()?i.pendingRequest?(i.formSubmitted=!0,!1):s():(i.focusInvalid(),!1)})),i)},valid:function(){if(t(this[0]).is("form"))return this.validate().form();var e=!0,i=t(this[0].form).validate();return this.each(function(){e&=i.element(this)}),e},removeAttrs:function(e){var i={},s=this;return t.each(e.split(/\s/),function(t,e){i[e]=s.attr(e),s.removeAttr(e)}),i},rules:function(e,i){var s=this[0];if(e){var n=t.data(s.form,"validator").settings,r=n.rules,a=t.validator.staticRules(s);switch(e){case"add":t.extend(a,t.validator.normalizeRule(i)),r[s.name]=a,i.messages&&(n.messages[s.name]=t.extend(n.messages[s.name],i.messages));break;case"remove":if(!i)return delete r[s.name],a;var u={};return t.each(i.split(/\s/),function(t,e){u[e]=a[e],delete a[e]}),u}}var o=t.validator.normalizeRules(t.extend({},t.validator.metadataRules(s),t.validator.classRules(s),t.validator.attributeRules(s),t.validator.staticRules(s)),s);if(o.required){var l=o.required;delete o.required,o=t.extend({required:l},o)}return o}}),t.extend(t.expr[":"],{blank:function(e){return!t.trim(""+e.value)},filled:function(e){return!!t.trim(""+e.value)},unchecked:function(t){return!t.checked}}),t.validator=function(e,i){this.settings=t.extend(!0,{},t.validator.defaults,e),this.currentForm=i,this.init()},t.validator.format=function(e,i){return 1==arguments.length?function(){var i=t.makeArray(arguments);return i.unshift(e),t.validator.format.apply(this,i)}:(arguments.length>2&&i.constructor!=Array&&(i=t.makeArray(arguments).slice(1)),i.constructor!=Array&&(i=[i]),t.each(i,function(t,i){e=e.replace(new RegExp("\\{"+t+"\\}","g"),i)}),e)},t.extend(t.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:!0,errorContainer:t([]),errorLabelContainer:t([]),onsubmit:!0,ignore:[],ignoreTitle:!1,onfocusin:function(t){this.lastActive=t,this.settings.focusCleanup&&!this.blockFocusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,t,this.settings.errorClass,this.settings.validClass),this.addWrapper(this.errorsFor(t)).hide())},onfocusout:function(t){this.checkable(t)||!(t.name in this.submitted)&&this.optional(t)||this.element(t)},onkeyup:function(t){(t.name in this.submitted||t==this.lastElement)&&this.element(t)},onclick:function(t){t.name in this.submitted?this.element(t):t.parentNode.name in this.submitted&&this.element(t.parentNode)},highlight:function(e,i,s){t(e).addClass(i).removeClass(s)},unhighlight:function(e,i,s){t(e).removeClass(i).addClass(s)}},setDefaults:function(e){t.extend(t.validator.defaults,e)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:t.validator.format("Please enter no more than {0} characters."),minlength:t.validator.format("Please enter at least {0} characters."),rangelength:t.validator.format("Please enter a value between {0} and {1} characters long."),range:t.validator.format("Please enter a value between {0} and {1}."),max:t.validator.format("Please enter a value less than or equal to {0}."),min:t.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function e(e){var i=t.data(this[0].form,"validator"),s="on"+e.type.replace(/^validate/,"");i.settings[s]&&i.settings[s].call(i,this[0])}this.labelContainer=t(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||t(this.currentForm),this.containers=t(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var i=this.groups={};t.each(this.settings.groups,function(e,s){t.each(s.split(/\s/),function(t,s){i[s]=e})});var s=this.settings.rules;t.each(s,function(e,i){s[e]=t.validator.normalizeRule(i)}),t(this.currentForm).validateDelegate(":text, :password, :file, select, textarea","focusin focusout keyup",e).validateDelegate(":radio, :checkbox, select, option","click",e),this.settings.invalidHandler&&t(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),t.extend(this.submitted,this.errorMap),this.invalid=t.extend({},this.errorMap),this.valid()||t(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var t=0,e=this.currentElements=this.elements();e[t];t++)this.check(e[t]);return this.valid()},element:function(e){e=this.clean(e),this.lastElement=e,this.prepareElement(e),this.currentElements=t(e);var i=this.check(e);return i?delete this.invalid[e.name]:this.invalid[e.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),i},showErrors:function(e){if(e){t.extend(this.errorMap,e),this.errorList=[];for(var i in e)this.errorList.push({message:e[i],element:this.findByName(i)[0]});this.successList=t.grep(this.successList,function(t){return!(t.name in e)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){t.fn.resetForm&&t(this.currentForm).resetForm(),this.submitted={},this.prepareForm(),this.hideErrors(),this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(t){var e=0;for(var i in t)e++;return e},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return 0==this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{t(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(t){}},findLastActive:function(){var e=this.lastActive;return e&&1==t.grep(this.errorList,function(t){return t.element.name==e.name}).length&&e},elements:function(){var e=this,i={};return t([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){return!this.name&&e.settings.debug&&window.console&&console.error("%o has no name assigned",this),!(this.name in i||!e.objectLength(t(this).rules()))&&(i[this.name]=!0,!0)})},clean:function(e){return t(e)[0]},errors:function(){return t(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=t([]),this.toHide=t([]),this.currentElements=t([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(t){this.reset(),this.toHide=this.errorsFor(t)},check:function(e){e=this.clean(e),this.checkable(e)&&(e=this.findByName(e.name).not(this.settings.ignore)[0]);var i=t(e).rules(),s=!1;for(var n in i){var r={method:n,parameters:i[n]};try{var a=t.validator.methods[n].call(this,e.value.replace(/\r/g,""),e,r.parameters);if("dependency-mismatch"==a){s=!0;continue}if(s=!1,"pending"==a)return void(this.toHide=this.toHide.not(this.errorsFor(e)));if(!a)return this.formatAndAdd(e,r),!1}catch(t){throw this.settings.debug&&window.console&&console.log("exception occured when checking element "+e.id+", check the '"+r.method+"' method",t),t}}if(!s)return this.objectLength(i)&&this.successList.push(e),!0},customMetaMessage:function(e,i){if(t.metadata){var s=this.settings.meta?t(e).metadata()[this.settings.meta]:t(e).metadata();return s&&s.messages&&s.messages[i]}},customMessage:function(t,e){var i=this.settings.messages[t];return i&&(i.constructor==String?i:i[e])},findDefined:function(){for(var t=0;t<arguments.length;t++)if(void 0!==arguments[t])return arguments[t]},defaultMessage:function(e,i){return this.findDefined(this.customMessage(e.name,i),this.customMetaMessage(e,i),!this.settings.ignoreTitle&&e.title||void 0,t.validator.messages[i],"<strong>Warning: No message defined for "+e.name+"</strong>")},formatAndAdd:function(t,e){var i=this.defaultMessage(t,e.method),s=/\$?\{(\d+)\}/g;"function"==typeof i?i=i.call(this,e.parameters,t):s.test(i)&&(i=jQuery.format(i.replace(s,"{$1}"),e.parameters)),this.errorList.push({message:i,element:t}),this.errorMap[t.name]=i,this.submitted[t.name]=i},addWrapper:function(t){return this.settings.wrapper&&(t=t.add(t.parent(this.settings.wrapper))),t},defaultShowErrors:function(){for(var t=0;this.errorList[t];t++){var e=this.errorList[t];this.settings.highlight&&this.settings.highlight.call(this,e.element,this.settings.errorClass,this.settings.validClass),this.showLabel(e.element,e.message)}if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(var t=0;this.successList[t];t++)this.showLabel(this.successList[t]);if(this.settings.unhighlight)for(var t=0,i=this.validElements();i[t];t++)this.settings.unhighlight.call(this,i[t],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return t(this.errorList).map(function(){return this.element})},showLabel:function(e,i){var s=this.errorsFor(e);s.length?(s.removeClass().addClass(this.settings.errorClass),s.attr("generated")&&s.html(i)):(s=t("<"+this.settings.errorElement+"/>").attr({for:this.idOrName(e),generated:!0}).addClass(this.settings.errorClass).html(i||""),this.settings.wrapper&&(s=s.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.append(s).length||(this.settings.errorPlacement?this.settings.errorPlacement(s,t(e)):s.insertAfter(e))),!i&&this.settings.success&&(s.text(""),"string"==typeof this.settings.success?s.addClass(this.settings.success):this.settings.success(s)),this.toShow=this.toShow.add(s)},errorsFor:function(e){var i=this.idOrName(e);return this.errors().filter(function(){return t(this).attr("for")==i})},idOrName:function(t){return this.groups[t.name]||(this.checkable(t)?t.name:t.id||t.name)},checkable:function(t){return/radio|checkbox/i.test(t.type)},findByName:function(e){var i=this.currentForm;return t(document.getElementsByName(e)).map(function(t,s){return s.form==i&&s.name==e&&s||null})},getLength:function(e,i){switch(i.nodeName.toLowerCase()){case"select":return t("option:selected",i).length;case"input":if(this.checkable(i))return this.findByName(i.name).filter(":checked").length}return e.length},depend:function(t,e){return!this.dependTypes[typeof t]||this.dependTypes[typeof t](t,e)},dependTypes:{boolean:function(t,e){return t},string:function(e,i){return!!t(e,i.form).length},function:function(t,e){return t(e)}},optional:function(e){return!t.validator.methods.required.call(this,t.trim(e.value),e)&&"dependency-mismatch"},startRequest:function(t){this.pending[t.name]||(this.pendingRequest++,this.pending[t.name]=!0)},stopRequest:function(e,i){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[e.name],i&&0==this.pendingRequest&&this.formSubmitted&&this.form()?(t(this.currentForm).submit(),this.formSubmitted=!1):!i&&0==this.pendingRequest&&this.formSubmitted&&(t(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(e){return t.data(e,"previousValue")||t.data(e,"previousValue",{old:null,valid:!0,message:this.defaultMessage(e,"remote")})}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},dateDE:{dateDE:!0},number:{number:!0},numberDE:{numberDE:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(e,i){e.constructor==String?this.classRuleSettings[e]=i:t.extend(this.classRuleSettings,e)},classRules:function(e){var i={},s=t(e).attr("class");return s&&t.each(s.split(" "),function(){this in t.validator.classRuleSettings&&t.extend(i,t.validator.classRuleSettings[this])}),i},attributeRules:function(e){var i={},s=t(e);for(var n in t.validator.methods){var r=s.attr(n);r&&(i[n]=r)}return i.maxlength&&/-1|2147483647|524288/.test(i.maxlength)&&delete i.maxlength,i},metadataRules:function(e){if(!t.metadata)return{};var i=t.data(e.form,"validator").settings.meta;return i?t(e).metadata()[i]:t(e).metadata()},staticRules:function(e){var i={},s=t.data(e.form,"validator");return s.settings.rules&&(i=t.validator.normalizeRule(s.settings.rules[e.name])||{}),i},normalizeRules:function(e,i){return t.each(e,function(s,n){if(n===!1)return void delete e[s];if(n.param||n.depends){var r=!0;switch(typeof n.depends){case"string":r=!!t(n.depends,i.form).length;break;case"function":r=n.depends.call(i,i)}r?e[s]=void 0===n.param||n.param:delete e[s]}}),t.each(e,function(s,n){e[s]=t.isFunction(n)?n(i):n}),t.each(["minlength","maxlength","min","max"],function(){e[this]&&(e[this]=Number(e[this]))}),t.each(["rangelength","range"],function(){e[this]&&(e[this]=[Number(e[this][0]),Number(e[this][1])])}),t.validator.autoCreateRanges&&(e.min&&e.max&&(e.range=[e.min,e.max],delete e.min,delete e.max),e.minlength&&e.maxlength&&(e.rangelength=[e.minlength,e.maxlength],delete e.minlength,delete e.maxlength)),e.messages&&delete e.messages,e},normalizeRule:function(e){if("string"==typeof e){var i={};t.each(e.split(/\s/),function(){i[this]=!0}),e=i}return e},addMethod:function(e,i,s){t.validator.methods[e]=i,t.validator.messages[e]=void 0!=s?s:t.validator.messages[e],i.length<3&&t.validator.addClassRules(e,t.validator.normalizeRule(e))},methods:{required:function(e,i,s){if(!this.depend(s,i))return"dependency-mismatch";switch(i.nodeName.toLowerCase()){case"select":var n=t(i).val();return n&&n.length>0;case"input":if(this.checkable(i))return this.getLength(e,i)>0;default:return t.trim(e).length>0}},remote:function(e,i,s){if(this.optional(i))return"dependency-mismatch";var n=this.previousValue(i);if(this.settings.messages[i.name]||(this.settings.messages[i.name]={}),n.originalMessage=this.settings.messages[i.name].remote,this.settings.messages[i.name].remote=n.message,s="string"==typeof s&&{url:s}||s,this.pending[i.name])return"pending";if(n.old===e)return n.valid;n.old=e;var r=this;this.startRequest(i);var a={};return a[i.name]=e,t.ajax(t.extend(!0,{url:s,mode:"abort",port:"validate"+i.name,dataType:"json",data:a,success:function(s){r.settings.messages[i.name].remote=n.originalMessage;var a=s===!0;if(a){var u=r.formSubmitted;r.prepareElement(i),r.formSubmitted=u,r.successList.push(i),r.showErrors()}else{var o={},l=s||r.defaultMessage(i,"remote");o[i.name]=n.message=t.isFunction(l)?l(e):l,r.showErrors(o)}n.valid=a,r.stopRequest(i,a)}},s)),"pending"},minlength:function(e,i,s){return this.optional(i)||this.getLength(t.trim(e),i)>=s},maxlength:function(e,i,s){return this.optional(i)||this.getLength(t.trim(e),i)<=s},rangelength:function(e,i,s){var n=this.getLength(t.trim(e),i);return this.optional(i)||n>=s[0]&&n<=s[1]},min:function(t,e,i){return this.optional(e)||t>=i},max:function(t,e,i){return this.optional(e)||t<=i},range:function(t,e,i){return this.optional(e)||t>=i[0]&&t<=i[1]},email:function(t,e){return this.optional(e)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(t)},url:function(t,e){return this.optional(e)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(t)},date:function(t,e){return this.optional(e)||!/Invalid|NaN/.test(new Date(t))},dateISO:function(t,e){return this.optional(e)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(t)},number:function(t,e){return this.optional(e)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(t)},digits:function(t,e){return this.optional(e)||/^\d+$/.test(t)},creditcard:function(t,e){if(this.optional(e))return"dependency-mismatch";if(/[^0-9-]+/.test(t))return!1;var i=0,s=0,n=!1;t=t.replace(/\D/g,"");for(var r=t.length-1;r>=0;r--){var a=t.charAt(r),s=parseInt(a,10);n&&(s*=2)>9&&(s-=9),i+=s,n=!n}return i%10==0},accept:function(t,e,i){return i="string"==typeof i?i.replace(/,/g,"|"):"png|jpe?g|gif",this.optional(e)||t.match(new RegExp(".("+i+")$","i"))},equalTo:function(e,i,s){var n=t(s).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){t(i).valid()});return e==n.val()}}}),t.format=t.validator.format}(jQuery),function(t){var e={};if(t.ajaxPrefilter)t.ajaxPrefilter(function(t,i,s){var n=t.port;"abort"==t.mode&&(e[n]&&e[n].abort(),e[n]=s)});else{var i=t.ajax;t.ajax=function(s){var n=("mode"in s?s:t.ajaxSettings).mode,r=("port"in s?s:t.ajaxSettings).port;return"abort"==n?(e[r]&&e[r].abort(),e[r]=i.apply(this,arguments)):i.apply(this,arguments)}}}(jQuery),function(t){t.extend(t.fn,{validateDelegate:function(e,i,s){return this.bind(i,function(i){var n=t(i.target);if(n.is(e))return s.apply(n,arguments)})}})}(jQuery);
/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName )
					return undefined;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);
/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: CN
 */
jQuery.extend(jQuery.validator.messages, {
    required: "该字段不能为空",
		remote: "请修正该字段",
		email: "请输入正确格式的电子邮件",
		url: "请输入合法的网址",
		date: "请输入合法的日期",
		dateISO: "请输入合法的日期 (ISO).",
		number: "请输入合法的数字",
		digits: "只能输入整数",
		creditcard: "请输入合法的信用卡号",
		equalTo: "请再次输入相同的值",
		accept: "请输入拥有合法后缀名的字符串",
		maxlength: jQuery.validator.format("请输入一个长度最多是 {0} 的字符串"),
		minlength: jQuery.validator.format("请输入一个长度最少是 {0} 的字符串"),
		rangelength: jQuery.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
		range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
		max: jQuery.validator.format("请输入一个最大为 {0} 的值"),
		min: jQuery.validator.format("请输入一个最小为 {0} 的值"),
    notnull:"不能为空"
});
$(document).ready(function() {
    /**
     * 身份证号码验证
     *
     */
    function isIdCardNo(num) {
        var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
        var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
        var varArray = new Array();
        var intValue;
        var lngProduct = 0;
        var intCheckDigit;
        var intStrLen = num.length;
        var idNumber = num;
        // initialize
        if ((intStrLen != 15) && (intStrLen != 18)) {
            return false;
        }
        // check and set value
        for (i = 0; i < intStrLen; i++) {
            varArray[i] = idNumber.charAt(i);
            if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
                return false;
            } else if (i < 17) {
                varArray[i] = varArray[i] * factorArr[i];
            }
        }
        if (intStrLen == 18) {
            //check date
            var date8 = idNumber.substring(6, 14);
            if (isDate8(date8) == false) {
                return false;
            }
            // calculate the sum of the products
            for (i = 0; i < 17; i++) {
                lngProduct = lngProduct + varArray[i];
            }
            // calculate the check digit
            intCheckDigit = parityBit[lngProduct % 11];
            // check last digit
            if (varArray[17] != intCheckDigit) {
                return false;
            }
        } else { //length is 15
            //check date
            var date6 = idNumber.substring(6, 12);
            if (isDate6(date6) == false) {
                return false;
            }
        }
        return true;
    }
    /**
     * 判断是否为“YYYYMM”式的时期
     *
     */
    function isDate6(sDate) {
        if (!/^[0-9]{6}$/.test(sDate)) {
            return false;
        }
        var year, month, day;
        year = sDate.substring(0, 4);
        month = sDate.substring(4, 6);
        if (year < 1700 || year > 2500) return false
        if (month < 1 || month > 12) return false
        return true
    }
    /**
     * 判断是否为“YYYYMMDD”式的时期
     *
     */
    function isDate8(sDate) {
        if (!/^[0-9]{8}$/.test(sDate)) {
            return false;
        }
        var year, month, day;
        year = sDate.substring(0, 4);
        month = sDate.substring(4, 6);
        day = sDate.substring(6, 8);
        var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if (year < 1700 || year > 2500) return false
        if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29;
        if (month < 1 || month > 12) return false
        if (day < 1 || day > iaMonthDays[month - 1]) return false
        return true
    }
    // 身份证号码验证
    $.validator.addMethod("idcardno", function(value, element) {
        return this.optional(element) || isIdCardNo(value);
    }, "请正确输入身份证号码");
    //字母数字
    $.validator.addMethod("alnum", function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
    }, "只能包括英文字母和数字");
    // 邮政编码验证
    $.validator.addMethod("zipcode", function(value, element) {
        var tel = /^[0-9]{6}$/;
        return this.optional(element) || (tel.test(value));
    }, "请正确填写邮政编码");
    // 汉字
    $.validator.addMethod("chcharacter", function(value, element) {
        var tel = /^[\u4e00-\u9fa5]+$/;
        return this.optional(element) || (tel.test(value));
    }, "请输入汉字");
    // 字符最小长度验证（一个中文字符长度为2）
    $.validator.addMethod("stringMinLength", function(value, element, param) {
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) || (length >= param);
    }, $.validator.format("长度不能小于{0}!"));
    // 字符最大长度验证（一个中文字符长度为2）
    $.validator.addMethod("stringMaxLength", function(value, element, param) {
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) || (length <= param);
    }, $.validator.format("长度不能大于{0}!"));
    // 字符验证
    $.validator.addMethod("string", function(value, element) {
        return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
    }, "不允许包含特殊符号!");
    // 手机号码验证
    $.validator.addMethod("mobile", function(value, element) {
        var length = value.length;
        return this.optional(element) || (length == 11 && /^1[1|2|3|4|5|6|7|8|9]\d{9}$/.test(value));
    }, "手机号码格式错误!");
    // 电话号码验证
    $.validator.addMethod("phone", function(value, element) {
        var tel = /^(\d{3,4}-?)?\d{7,9}$/g;
        return this.optional(element) || (tel.test(value));
    }, "电话号码格式错误!");
    // 邮政编码验证
    $.validator.addMethod("zipCode", function(value, element) {
        var tel = /^[0-9]{6}$/;
        return this.optional(element) || (tel.test(value));
    }, "邮政编码格式错误!");
    // 必须以特定字符串开头验证
    $.validator.addMethod("begin", function(value, element, param) {
        var begin = new RegExp("^" + param);
        return this.optional(element) || (begin.test(value));
    }, $.validator.format("必须以 {0} 开头!"));
    // 验证两次输入值是否不相同
    $.validator.addMethod("notEqualTo", function(value, element, param) {
        return value != $(param).val();
    }, $.validator.format("两次输入不能相同!"));
    // 验证值不允许与特定值等于
    $.validator.addMethod("notEqual", function(value, element, param) {
        return value != param;
    }, $.validator.format("输入值不允许为{0}!"));
    // 验证值必须大于特定值(不能等于)
    $.validator.addMethod("gt", function(value, element, param) {
        return value > param;
    }, $.validator.format("输入值必须大于{0}!"));
    // 验证值小数位数不能超过两位
    $.validator.addMethod("decimal", function(value, element) {
                var decimal = /^-?\d+(\.\d{1,2})?$/;
                return this.optional(element) || (decimal.test(value));
	}, "小数位数不能超过两位");
    // 姓名支持“尼格买提·热合曼”
    $.validator.addMethod("nmcharacter", function(value, element) {
        var tel = /^[·\u4E00-\u9FA5]+$/;
        return this.optional(element) || (tel.test(value));
    }, "请输入正确的姓名格式");


/**
 * Below added by joseph for Shiqiao
 *
 */
    // Select 必选验证 (针对ligerForm 原生selet option)
    function isSelected (selectVal) {
        if (selectVal !='-1' && selectVal != "请选择" && $.trim(selectVal) != "") {return true;}
        else {return false};
    }
    $.validator.addMethod("select", function (value, element) {
            return this.optional(element) || isSelected(value);
            // return isSelected(value);
        },
        "请选择"
    );
    // combobox select (ligerui的 combobox)
    $.validator.addMethod("comboSelect", function (value, element) {
            return value && value.length > 0;
        },
        "请选择"
    );
    // 手机号码和座机验证
    $.validator.addMethod("mobileAndFixedPhone", function(value, element) {
        var length = value.length;
        var telReg=/^(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)$/;
        return this.optional(element) || ((length == 11 && /^1[3|4|5|7|8]\d{9}$/.test(value)) || telReg.test(value));
    }, "手机或者座机号码格式错误!");
    // 座机验证
    $.validator.addMethod("fixedPhone", function(value, element) {
        var length = value.length;
        var telReg=/^(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)$/;
        return this.optional(element) || (telReg.test(value));
    }, "座机号码格式错误!");

    //仅支持数字和中划线
    $.validator.addMethod("numberAndMiddleLine", function(value, element) {
        var length = value.length;
        var telReg=/^[\d\-]*$/;
        return this.optional(element) || (telReg.test(value));
    }, "仅支持数字和中划线");

    // 护照验证
    jQuery.validator.addMethod("passport", function(value, element) {
        var re1 = /^[a-zA-Z]{5,17}$/;
        var re2 = /^[a-zA-Z0-9]{5,17}$/;
        return this.optional(element) || (re2.test(value)) || re1.test(value);

    }, "护照格式不正确");

    // 港澳通行证验证
    jQuery.validator.addMethod("HKMacao", function(value, element) {
        var re = /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/;
        return this.optional(element) || (re.test(value));
    }, "港澳通行证格式不正确");

    // 台湾通行证验证
    jQuery.validator.addMethod("taiwan", function(value, element) {
        var re1 = /^[0-9]{8}$/;
        var re2 = /^[0-9]{10}$/;
        return this.optional(element) || (re1.test(value)) || (re2.test(value))
    }, "台湾通行证格式不正确");

    $.metadata.setType("attr", "validate");
});
jQuery.extend({
    createUploadIframe: function(id, uri)
	{
		//create frame
		var frameId = 'jUploadFrame' + id;
		var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
		if(window.ActiveXObject)
		{
			if(typeof uri== 'boolean'){
				iframeHtml += ' src="' + 'javascript:false' + '"';

			}
			else if(typeof uri== 'string'){
				iframeHtml += ' src="' + uri + '"';

			}	
		}
		iframeHtml += ' />';
		jQuery(iframeHtml).appendTo(document.body);

		return jQuery('#' + frameId).get(0);			
    },
    createUploadForm: function(id,fileElementId,data,fileElement)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		if(data)
		{
			for(var i in data)
			{
				jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
			}			
		}
		/*var oldElement;
		if(fileElement == null)
			oldElement = jQuery('#' + fileElementId);
		else
			oldElement = fileElement;
		
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);*/

	    if(typeof(fileElementId) == 'string'){  
	        fileElementId = [fileElementId];  
	    }  
	    for(var i in fileElementId){  
	        var oldElement = jQuery('#' + fileElementId[i]);  
	        var newElement = jQuery(oldElement).clone();  
	        jQuery(oldElement).attr('id', fileId);  
	        jQuery(oldElement).before(newElement);  
	        jQuery(oldElement).appendTo(form);  
	    }  
		
		//set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data),s.fileElement);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 // xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
					 // changed by joseph ：iframe被第三方插件注入标签导致读取json出问题
					 xml.responseText = io.contentWindow.document.body?getInnerJson(io.contentWindow.document.body):null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 // xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
					 xml.responseText = io.contentDocument.document.body?getInnerJson(io.contentDocument.document.body):null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
								reduceFileInputs();
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											jQuery(io).remove();
											jQuery(form).remove();	
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        //added by joseph for shiqiao | 恢复成原input
        function reduceFileInputs() {
        	$('[type=file]', form).each(function(index, el) {
        		var inputName = $(el).attr('name');
        		$('#'+inputName).replaceWith(el);
        		$(el).attr('id', inputName);
        		$(el).trigger('uploaded');
        	});
        };
        //added by joseph for shiqiao | 获取iframe里面的json（除掉script以及其它html标签）
        function getInnerJson(element) {
            return jQuery(element).contents().filter(function() {
                return this.nodeType === 3;
                }).text();
        };
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{

			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
            if(form.encoding)
			{
				jQuery(form).attr('encoding', 'multipart/form-data');      			
            }
            else
			{	
				jQuery(form).attr('enctype', 'multipart/form-data');			
            }			
            jQuery(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
		
		jQuery('#' + frameId).load(uploadCallback);
        return {abort: function(){
			try
			{
				jQuery('#' + frameId).remove();
				jQuery(form).remove();
			}
			catch(e){}
		}};
    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
		
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    },
	
	handleError: function( s, xml, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error )
			s.error( xml, status, e );

		// Fire the global callback
		if ( s.global )
			jQuery.event.trigger( "ajaxError", [xml, s, e] );
	}
});
function transitionEnd(){var e=document.createElement("bootstrap");var t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var n in t){if(e.style[n]!==undefined){return{end:t[n]}}}return false}(function(e){e.fn.smartZoom=function(t){function r(e){}function s(e,t){var r=n.data("smartZoomData");if(r.currentWheelDelta*t<0)r.currentWheelDelta=0;r.currentWheelDelta+=t;i.zoom(r.mouseWheelDeltaFactor*r.currentWheelDelta,{x:e.pageX,y:e.pageY})}function o(e){e.preventDefault()}function u(){var e=n.data("smartZoomData");if(e.settings.mouseMoveEnabled!=true||e.settings.moveCursorEnabled!=true)return;var t=S();var r=t.width/e.originalSize.width;if(parseInt(r*100)>parseInt(e.adjustedPosInfos.scale*100))n.css({cursor:"move"});else n.css({cursor:"default"})}function a(e){m(e.pageX,e.pageY)}function f(t){t.preventDefault();e(document).on("mousemove.smartZoom",l);e(document).bind("mouseup.smartZoom",c);var r=n.data("smartZoomData");r.moveCurrentPosition=new A(t.pageX,t.pageY);r.moveLastPosition=new A(t.pageX,t.pageY)}function l(e){var t=n.data("smartZoomData");if(t.mouseMoveForPan||!t.mouseMoveForPan&&t.moveCurrentPosition.x!=e.pageX&&t.moveCurrentPosition.y!=e.pageY){t.mouseMoveForPan=true;v(e.pageX,e.pageY,0,false)}}function c(t){var r=n.data("smartZoomData");if(r.mouseMoveForPan){r.mouseMoveForPan=false;if(r.moveLastPosition.distance(r.moveCurrentPosition)>4){var i=r.moveLastPosition.interpolate(r.moveCurrentPosition,-4);v(i.x,i.y,500,true)}else{v(r.moveLastPosition.x,r.moveLastPosition.y,0,true)}}else if(r.settings.zoomOnSimpleClick){m(t.pageX,t.pageY)}e(document).unbind("mousemove.smartZoom");e(document).unbind("mouseup.smartZoom")}function h(t){t.preventDefault();e(document).unbind("touchmove.smartZoom");e(document).unbind("touchend.smartZoom");e(document).bind("touchmove.smartZoom",p);e(document).bind("touchend.smartZoom",d);var r=t.originalEvent.touches;var i=r[0];var s=n.data("smartZoomData");s.touch.touchMove=false;s.touch.touchPinch=false;s.moveCurrentPosition=new A(i.pageX,i.pageY);s.moveLastPosition=new A(i.pageX,i.pageY);s.touch.lastTouchPositionArr=new Array;var o;var u=r.length;for(var a=0;a<u;++a){o=r[a];s.touch.lastTouchPositionArr.push(new A(o.pageX,o.pageY))}}function p(e){e.preventDefault();var t=n.data("smartZoomData");var r=e.originalEvent.touches;var s=r.length;var o=r[0];if(s==1&&!t.touch.touchPinch&&t.settings.touchMoveEnabled==true){if(!t.touch.touchMove){var u=t.touch.lastTouchPositionArr[0];if(u.distance(new A(o.pageX,o.pageY))<3){return}else t.touch.touchMove=true}v(o.pageX,o.pageY,0,false)}else if(s==2&&!t.touch.touchMove&&t.settings.pinchEnabled==true){t.touch.touchPinch=true;var a=r[1];var f=t.touch.lastTouchPositionArr[0];var l=t.touch.lastTouchPositionArr[1];var c=new A(o.pageX,o.pageY);var h=new A(a.pageX,a.pageY);var p=c.distance(h);var d=f.distance(l);var m=p-d;if(Math.abs(m)<3)return;var g=new A((c.x+h.x)/2,(c.y+h.y)/2);var y=S();var b=t.originalSize;var w=y.width/b.width;var E=p/d;var x=y.width*E/b.width;i.zoom(x-w,g,0);t.touch.lastTouchPositionArr[0]=c;t.touch.lastTouchPositionArr[1]=h}}function d(t){t.preventDefault();var r=t.originalEvent.touches.length;if(r==0){e(document).unbind("touchmove.smartZoom");e(document).unbind("touchend.smartZoom")}var i=n.data("smartZoomData");if(i.touch.touchPinch)return;if(i.touch.touchMove){if(i.moveLastPosition.distance(i.moveCurrentPosition)>2){var s=i.moveLastPosition.interpolate(i.moveCurrentPosition,-4);v(s.x,s.y,500,true)}}else{if(i.settings.dblTapEnabled==true&&i.touch.lastTouchEndTime!=0&&(new Date).getTime()-i.touch.lastTouchEndTime<400){var o=i.touch.lastTouchPositionArr[0];m(o.x,o.y)}i.touch.lastTouchEndTime=(new Date).getTime()}}function v(e,t,i,s){g(r.PAN);var o=n.data("smartZoomData");o.moveLastPosition.x=o.moveCurrentPosition.x;o.moveLastPosition.y=o.moveCurrentPosition.y;var u=n.offset();var a=S();var f=u.left+(e-o.moveCurrentPosition.x);var l=u.top+(t-o.moveCurrentPosition.y);var c=y(f,l,a.width,a.height);x(r.PAN,r.START,false);E(n,c.x,c.y,a.width,a.height,i,s==true?function(){x(r.PAN,r.END,false)}:null);o.moveCurrentPosition.x=e;o.moveCurrentPosition.y=t}function m(e,t){var r=n.data("smartZoomData");var s=r.originalSize;var o=S();var u=o.width/s.width;var a=r.adjustedPosInfos.scale;var f=parseFloat(r.settings.dblClickMaxScale);var l;if(u.toFixed(2)>f.toFixed(2)||Math.abs(f-u)>Math.abs(u-a)){l=f-u}else{l=a-u}i.zoom(l,{x:e,y:t})}function g(t){var r=n.data("smartZoomData");if(r.transitionObject){if(r.transitionObject.cssAnimHandler)n.off(e.support.transition,r.transitionObject.cssAnimTimer);var i=r.originalSize;var s=S();var o=new Object;o[r.transitionObject.transition]="all 0s";if(r.transitionObject.css3dSupported){o[r.transitionObject.transform]="translate3d("+s.x+"px, "+s.y+"px, 0) scale3d("+s.width/i.width+","+s.height/i.height+", 1)"}else{o[r.transitionObject.transform]="translateX("+s.x+"px) translateY("+s.y+"px) scale("+s.width/i.width+","+s.height/i.height+")"}n.css(o)}else{n.stop()}u();if(t!=null)x(t,"",true)}function y(e,t,r,i){var s=n.data("smartZoomData");var o=Math.min(s.adjustedPosInfos.top,t);o+=Math.max(0,s.adjustedPosInfos.top+s.adjustedPosInfos.height-(o+i));var u=Math.min(s.adjustedPosInfos.left,e);u+=Math.max(0,s.adjustedPosInfos.left+s.adjustedPosInfos.width-(u+r));return new A(u.toFixed(2),o.toFixed(2))}function b(e){n.unbind("load.smartZoom");i.init.apply(n,[e.data.arguments])}function w(){var e=n.data("smartZoomData");var t=e.containerDiv;var r=e.originalSize;var i=t.parent().offset();var s=C(e.settings.left,i.left,t.parent().width());var o=C(e.settings.top,i.top,t.parent().height());t.offset({left:s,top:o});t.width(N(e.settings.width,t.parent().width(),s-i.left));t.height(N(e.settings.height,t.parent().height(),o-i.top));var a=L(t);var f=Math.min(Math.min(a.width/r.width,a.height/r.height),1).toFixed(2);var l=r.width*f;var c=r.height*f;e.adjustedPosInfos={left:(a.width-l)/2+i.left,top:(a.height-c)/2+i.top,width:l,height:c,scale:f};g();E(n,e.adjustedPosInfos.left,e.adjustedPosInfos.top,l,c,0,function(){n.css("visibility","visible")});u()}function E(t,r,i,s,o,u,a){var f=n.data("smartZoomData");var l=f.containerDiv.offset();var c=r-l.left;var h=i-l.top;if(f.transitionObject!=null){var p=f.originalSize;var d=new Object;d[f.transitionObject.transform+"-origin"]="0 0";d[f.transitionObject.transition]="all "+u/1e3+"s ease-out";if(f.transitionObject.css3dSupported)d[f.transitionObject.transform]="translate3d("+c+"px, "+h+"px, 0) scale3d("+s/p.width+","+o/p.height+", 1)";else d[f.transitionObject.transform]="translateX("+c+"px) translateY("+h+"px) scale("+s/p.width+","+o/p.height+")";if(a!=null){f.transitionObject.cssAnimHandler=a;t.one(e.support.transition.end,f.transitionObject.cssAnimHandler)}t.css(d)}else{t.animate({"margin-left":c,"margin-top":h,width:s,height:o},{duration:u,easing:f.settings.easing,complete:function(){if(a!=null)a()}})}}function S(e){var t=n.data("smartZoomData");var r=n.width();var i=n.height();var s=n.offset();var o=parseInt(s.left);var u=parseInt(s.top);var a=t.containerDiv.offset();if(e!=true){o=parseInt(o)-a.left;u=parseInt(u)-a.top}if(t.transitionObject!=null){var f=n.css(t.transitionObject.transform);if(f&&f!=""&&f.search("matrix")!=-1){var l;var c;if(f.search("matrix3d")!=-1){c=f.replace("matrix3d(","").replace(")","").split(",");l=c[0]}else{c=f.replace("matrix(","").replace(")","").split(",");l=c[3];o=parseFloat(c[4]);u=parseFloat(c[5]);if(e){o=parseFloat(o)+a.left;u=parseFloat(u)+a.top}}r=l*r;i=l*i}}return{x:o,y:u,width:r,height:i}}function x(e,t,i){var s=n.data("smartZoomData");var o="";if(i==true&&s.currentActionType!=e){o=s.currentActionType+"_"+r.END;s.currentActionType="";s.currentActionStep=""}else{if(s.currentActionType!=e||s.currentActionStep==r.END){s.currentActionType=e;s.currentActionStep=r.START;o=s.currentActionType+"_"+s.currentActionStep}else if(s.currentActionType==e&&t==r.END){s.currentActionStep=r.END;o=s.currentActionType+"_"+s.currentActionStep;s.currentActionType="";s.currentActionStep=""}}if(o!=""){var u=jQuery.Event(o);u.targetRect=S(true);u.scale=u.targetRect.width/s.originalSize.width;n.trigger(u)}}function T(){var t=document.body||document.documentElement;var n=t.style;var r=["transition","WebkitTransition","MozTransition","MsTransition","OTransition"];var i=["transition","-webkit-transition","-moz-transition","-ms-transition","-o-transition"];var s=["transform","-webkit-transform","-moz-transform","-ms-transform","-o-transform"];var o=r.length;var u;for(var a=0;a<o;a++){if(n[r[a]]!=null){transformStr=s[a];var f=e('<div style="position:absolute;">Translate3d Test</div>');e("body").append(f);u=new Object;u[s[a]]="translate3d(20px,0,0)";f.css(u);css3dSupported=f.offset().left-e("body").offset().left==20;f.empty().remove();if(css3dSupported){return{transition:i[a],transform:s[a],css3dSupported:css3dSupported}}}}return null}function N(e,t,n){if(e.search&&e.search("%")!=-1)return(t-n)*(parseInt(e)/100);else return parseInt(e)}function C(e,t,n){if(e.search&&e.search("%")!=-1)return t+n*(parseInt(e)/100);else return t+parseInt(e)}function k(){w()}function L(e){var t=e.offset();if(!t)return null;var n=t.left;var r=t.top;return{x:n,y:r,width:e.outerWidth(),height:e.outerHeight()}}function A(e,t){this.x=e;this.y=t;this.toString=function(){return"(x="+this.x+", y="+this.y+")"};this.interpolate=function(e,t){var n=t*this.x+(1-t)*e.x;var r=t*this.y+(1-t)*e.y;return new A(n,r)};this.distance=function(e){return Math.sqrt(Math.pow(e.y-this.y,2)+Math.pow(e.x-this.x,2))}}var n=this;r.ZOOM="SmartZoom_ZOOM";r.PAN="SmartZoom_PAN";r.START="START";r.END="END";r.DESTROYED="SmartZoom_DESTROYED";var i={init:function(t){if(n.data("smartZoomData"))return;settings=e.extend({top:"0",left:"0",width:"100%",height:"100%",easing:"smartZoomEasing",initCallback:null,maxScale:3,dblClickMaxScale:1.8,mouseEnabled:true,scrollEnabled:true,dblClickEnabled:true,mouseMoveEnabled:true,moveCursorEnabled:true,adjustOnResize:true,touchEnabled:true,dblTapEnabled:true,zoomOnSimpleClick:false,pinchEnabled:true,touchMoveEnabled:true,containerBackground:"#FFFFFF",containerClass:""},t);var r=n.attr("style");var i="smartZoomContainer"+(new Date).getTime();var u=e('<div id="'+i+'" class="'+settings.containerClass+'"></div>');n.before(u);n.remove();u=e("#"+i);u.css({overflow:"hidden"});if(settings.containerClass=="")u.css({"background-color":settings.containerBackground});u.append(n);var l=new Object;l.lastTouchEndTime=0;l.lastTouchPositionArr=null;l.touchMove=false;l.touchPinch=false;n.data("smartZoomData",{settings:settings,containerDiv:u,originalSize:{width:n.width(),height:n.height()},originalPosition:n.offset(),transitionObject:T(),touch:l,mouseWheelDeltaFactor:.15,currentWheelDelta:0,adjustedPosInfos:null,moveCurrentPosition:null,moveLastPosition:null,mouseMoveForPan:false,currentActionType:"",initialStyles:r,currentActionStep:""});w();if(settings.touchEnabled==true)n.bind("touchstart.smartZoom",h);if(settings.mouseEnabled==true){if(settings.mouseMoveEnabled==true)n.bind("mousedown.smartZoom",f);if(settings.scrollEnabled==true){u.bind("mousewheel.smartZoom",s);u.bind("mousewheel.smartZoom DOMMouseScroll.smartZoom",o)}if(settings.dblClickEnabled==true&&settings.zoomOnSimpleClick==false)u.bind("dblclick.smartZoom",a)}document.ondragstart=function(){return false};if(settings.adjustOnResize==true)e(window).bind("resize.smartZoom",k);if(settings.initCallback!=null)settings.initCallback.apply(this,n)},zoom:function(e,t,i){var s=n.data("smartZoomData");var o;var a;if(!t){var f=L(s.containerDiv);o=f.x+f.width/2;a=f.y+f.height/2}else{o=t.x;a=t.y}g(r.ZOOM);var l=S(true);var c=s.originalSize;var h=l.width/c.width+e;h=Math.max(s.adjustedPosInfos.scale,h);h=Math.min(s.settings.maxScale,h);var p=c.width*h;var d=c.height*h;var v=o-l.x;var m=a-l.y;var b=p/l.width;var w=l.x-(v*b-v);var T=l.y-(m*b-m);var N=y(w,T,p,d);if(i==null)i=700;x(r.ZOOM,r.START,false);E(n,N.x,N.y,p,d,i,function(){s.currentWheelDelta=0;u();x(r.ZOOM,r.END,false)})},pan:function(e,t,i){if(e==null||t==null)return;if(i==null)i=700;var s=n.offset();var o=S();var u=y(s.left+e,s.top+t,o.width,o.height);if(u.x!=s.left||u.y!=s.top){g(r.PAN);x(r.PAN,r.START,false);E(n,u.x,u.y,o.width,o.height,i,function(){x(r.PAN,r.END,false)})}},destroy:function(){var t=n.data("smartZoomData");if(!t)return;g();var i=t.containerDiv;n.unbind("mousedown.smartZoom");n.bind("touchstart.smartZoom");i.unbind("mousewheel.smartZoom");i.unbind("dblclick.smartZoom");i.unbind("mousewheel.smartZoom DOMMouseScroll.smartZoom");e(window).unbind("resize.smartZoom");e(document).unbind("mousemove.smartZoom");e(document).unbind("mouseup.smartZoom");e(document).unbind("touchmove.smartZoom");e(document).unbind("touchend.smartZoom");n.css({cursor:"default"});i.before(n);E(n,t.originalPosition.left,t.originalPosition.top,t.originalSize.width,t.originalSize.height,5);n.removeData("smartZoomData");i.remove();n.attr("style",t.initialStyles);n.trigger(r.DESTROYED)},isPluginActive:function(){return n.data("smartZoomData")!=undefined}};if(i[t]){return i[t].apply(this,Array.prototype.slice.call(arguments,1))}else if(typeof t==="object"||!t){if(n[0].tagName.toLowerCase()=="img"&&!n[0].complete){n.bind("load.smartZoom",{arguments:arguments[0]},b)}else{i.init.apply(n,[arguments[0]])}}else{e.error("Method "+t+" does not exist on e-smartzoom jquery plugin")}}})(jQuery);(function(e){e.extend(e.easing,{smartZoomEasing:function(t,n,r,i,s){return e.easing["smartZoomOutQuad"](t,n,r,i,s)},smartZoomOutQuad:function(e,t,n,r,i){return-r*(t/=i)*(t-2)+n}})})(jQuery);(function(e){function t(t){var n=t||window.event,r=[].slice.call(arguments,1),i=0,s=true,o=0,u=0;t=e.event.fix(n);t.type="mousewheel";if(n.wheelDelta){i=n.wheelDelta/120}if(n.detail){i=-n.detail/3}u=i;if(n.axis!==undefined&&n.axis===n.HORIZONTAL_AXIS){u=0;o=-1*i}if(n.wheelDeltaY!==undefined){u=n.wheelDeltaY/120}if(n.wheelDeltaX!==undefined){o=-1*n.wheelDeltaX/120}r.unshift(t,i,o,u);return(e.event.dispatch||e.event.handle).apply(this,r)}var n=["DOMMouseScroll","mousewheel"];if(e.event.fixHooks){for(var r=n.length;r;){e.event.fixHooks[n[--r]]=e.event.mouseHooks}}e.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var e=n.length;e;){this.addEventListener(n[--e],t,false)}}else{this.onmousewheel=t}},teardown:function(){if(this.removeEventListener){for(var e=n.length;e;){this.removeEventListener(n[--e],t,false)}}else{this.onmousewheel=null}}};e.fn.extend({mousewheel:function(e){return e?this.bind("mousewheel",e):this.trigger("mousewheel")},unmousewheel:function(e){return this.unbind("mousewheel",e)}})})(jQuery);$.fn.emulateTransitionEnd=function(e){var t=false,n=this;$(this).one($.support.transition.end,function(){t=true});var r=function(){if(!t)$(n).trigger($.support.transition.end)};setTimeout(r,e);return this};$(function(){$.support.transition=transitionEnd()})

if(!Date.prototype.Format)
{
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
};

//全站Ajax设置无缓存
$.ajaxSetup({
    cache: false
});
$(function () {
    // 标题下面没有表单可填写，就隐藏标题
    var $fieldCaption=$(".tabel_col .caption");
    $fieldCaption.each(function(index, el) {
        if ($(this).next("div").children('div').hasClass('fieldBox')) return;
        var $fieldBox=$(this).next(".fieldBox");
        if (!$fieldBox.length) $(this).hide();
    });
    $(".iframeBody iframe").load(function() {
        try{
            $(this).contents().find("body").addClass('iframeBody_L2')
        }
        catch(err){}
    });
    $(".liger_tip").ligerTip();
    $(".l-dialog-btn-cancel").click(function() {
        var ligeruiID=$(this).parents(".l-dialog").attr('ligeruiid');
        if (ligeruiID) {
            var dialog=liger.get(ligeruiID);
            dialog.hide();
        };
        if (frameElement && frameElement.dialog) frameElement.dialog.hidden();
    });

    // 搜索框 按回车键的时候 可搜索（只有一个输入框和按钮）
    $("form.titSearchBar").each(function(index, el) {
        if ($(this).find('input[type=text]').length==1) {
            $(this).submit(function(event) {
                event.preventDefault();
                $(this).find('.sq-search-button').click();
            });
        };
    });
    //点击F5键，或者Crtl+R键 刷新的时候，只刷新当前Tab
    $(document).keydown(function(event) {
        var navTab=top.tab;
        if (!navTab) return;
        var keycode=event.keyCode;
        if (keycode==116) {
            event.preventDefault();
            navTab.reload(navTab.getSelectedTabItemID());
        }
        //Ctrl键和r键组合 导致刷新页面
        // else if (keycode==17) {
        //     $(document).keydown(function(event) {
        //         var keycode2=event.keyCode;
        //         if (keycode2==82) {
        //             event.preventDefault();
        //             navTab.reload(navTab.getSelectedTabItemID());
        //         };
        //     });
        // };
    });
    // 按“回车键”，触发搜索（针对.ui-textbox）
    $(".searchArea .ui-textbox").on('keydown', function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            $(this).parents(".searchArea").find('#searchBtn').click();
        };
    });
    $('[data-tofix]').each(function(index, el) {
        var Precision = $(this).data('tofix');
        $(this).toFixNumber(Precision,
            {
                onToFix: function () {
                    top.$.ligerDialog.SQalert({SQ_type: "warning", content: "小数点后不能超过"+Precision+"位数！"});
                }
            }
        );
    });
    //表单的label超出范围 显示省略号，并已toolTip的方式显示全部内容
    $('[role="ligertip"]').each(function(index, el) {
        var content = $(el).text();
        $(el).attr('title', content).grid_ligerTip();
    });
    $('.fieldset1.tabel_col .fieldBox .label').each(function(index, el) {
        if (el.scrollWidth <= el.clientWidth) return;
        if ($(el).attr('role') == 'ligertip') return; //手动添加了 就忽略
        if ($(el).attr('role') == 'textclip') return; //role="textclip"若允许折行 就忽略
        var content = $(el).text();
        $(el).attr('title', content).grid_ligerTip();
    });
    // 表单的label超出范围时 是否允许折行
    $('[role="textclip"]').each(function(index, el) {
        $(el).css({
            'white-space': 'normal',
            'text-overflow': 'clip'
        });
    });
    //ligerGrid里面的下拉框，绑定事件
    //注：render的时候用SQ.dropLinks()方法，把里面的按钮（a）包装一下
    $('.sq-grid').on('click', '.dropLinks .dropBtn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var $dropLinks = $(this).parent('.dropLinks'),
            $dropList = $(this).siblings('.dropList').clone(),
            pos_top=$(this).offset().top + $(this).outerHeight(),
            pos_right=$(window).width() - $(this).offset().left - $(this).outerWidth();
        if ($dropLinks.hasClass('open')) {
            _close();
            return;
        } else {
            _close();
            $dropLinks.addClass('open');
        };
        $dropList.appendTo('body').addClass('Fix_dropLinks').css({
            top: pos_top,
            right: pos_right
        });
        $(document).click(function(event) {
            _close()
        });
        function _close() {
            $('.Fix_dropLinks').remove();
            $('.dropLinks').removeClass('open')
        }
    });
})
/**
 * 嵌套子窗口（iframe），高度调整
 * 注：pageInApp 是一级之窗口创建的对象，作为二级之窗口调用的接口
 * 注：pageInTab 是一级子窗口里创建的标签组（如果有）（ligerTab对象）
 */
function SetIframe_height () {
    if (parent && parent.mainApp && parent.mainApp.parentTab && parent.mainApp.parentTab.onResize) {
        parent.mainApp.parentTab.onResize();
    }else
    if (parent && parent.pageInApp && parent.pageInApp.pageInTab && parent.pageInApp.pageInTab.onResize) {
        parent.pageInApp.pageInTab.onResize();
        if (top.mainApp && top.mainApp.parentTab && top.mainApp.parentTab.onResize) {
            top.mainApp.parentTab.onResize();
        }
    };
}
function GET_minIframeHeight () { //只针对有二级ligerTab | 用在了ligerTab的minIframeHeight设置上
    var minIframeHeight=$(parent.window).height()-172;
    return minIframeHeight;
}
// Dialog的内容是url 嵌入的时候，用来调整iframe高度
function SET_popupIframeHeight () {
    if (!$("body").hasClass('iframeBody_popup')) $("body").addClass('iframeBody_popup');
    $(frameElement).height($("html").outerHeight())
}
function Add_navTab (tabid, text, url, receive) {
    if (top && top.mainApp && top.mainApp.parentTab && top.mainApp.f_addTab) {
        top.mainApp.f_addTab(tabid, text, url);
        var iframe=top.$("#"+tabid).get(0);
        iframe.W2W = {callback: null, data: null};
        if (typeof(receive)=="function") { //如果有callback，就绑定到iframe对象上
            iframe.W2W.callback = receive;
        } else if(receive){
            iframe.W2W.data = receive;
        };
    }else{
        window.open(url);
    };
}
function Remove_navTab (tabid) {
    if (top && top.mainApp && top.mainApp.parentTab) {
        var TAB=top.mainApp.parentTab;
        if (tabid) {
            TAB.removeTabItem(tabid);
        }else{ //没有传tabid就默认关闭当前tab
            var currentTabid=TAB.getSelectedTabItemID();
            var callback = GET_W2Wcallback (currentTabid);
            TAB.removeTabItem(currentTabid);
            callback && callback(); //移除Tab之后，执行callback
        };
    }else{
        return;
    };
}
function GET_W2W (tabid) { //可以指定具体的tabid，如果没有指定，默认当前tab | Add_navTab()的时候添加的receive
    if (top.mainApp && top.mainApp.parentTab) {
        var TabID = tabid;
        if (tabid == undefined ) TabID=top.mainApp.parentTab.getSelectedTabItemID();
        return top.$("#"+TabID).get(0).W2W;
    }
}
function GET_W2Wcallback (tabid) { //可以指定具体的tabid，如果没有指定，默认当前tab | Add_navTab()的时候添加的receive
    if (top && top.mainApp && top.mainApp.parentTab) {
        var TabID = tabid;
        if (tabid == undefined ) TabID=top.mainApp.parentTab.getSelectedTabItemID();
        var Tabiframe=top.$("#"+TabID).get(0);
        if (Tabiframe.W2W && Tabiframe.W2W.callback) {
            var callback=Tabiframe.W2W.callback;
        }
        return callback;
    }
}
//金额 用逗号 隔开。数字格式化
function FormatMoney(s, n){
   n = n > 0 && n <= 20 ? n : 2;
   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
   var l = s.split(".")[0].split("").reverse(),
   r = s.split(".")[1];
   t = "";
   for(i = 0; i < l.length; i ++ )
   {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
   }
   return t.split("").reverse().join("") + "." + r;
}
//金额 用逗号 隔开 -- 还原
function ReformatMoney(s){
   return parseFloat(s.replace(/[^\d\.-]/g, ""));
}
//是否正整数
function isInteger(number){
    return number > 0 && String(number).split('.')[1] == undefined
}

//是否是数字
function isNumber(number){
    return typeof number === 'number'
}

//弹框提示
function ligerDialogWarn (info,timeout) {
    var dialog = $.ligerDialog.warn(info);
    if (timeout && isInteger(timeout)) {
        setTimeout(function () {
            dialog.hide();
        },timeout)
    };
    return dialog;
}
function ligerDialogSuc (info,timeout) {
    var dialog = $.ligerDialog.success(info);
    if (timeout && isInteger(timeout)) {
        setTimeout(function () {
            dialog.hide();
        },timeout)
    };
    return dialog;
}
function ligerDialogWait (info,timeout) {
    var dialog = $.ligerDialog.waitting(info);
    if (timeout && isInteger(timeout)) {
        setTimeout(function () {
            dialog.hide();
        },timeout)
    };
    return dialog;
}
$.ligerDialog.SQopen = function (p){
    var onLoaded_funcs = p.onLoaded ? [p.onLoaded] : []; //事件队列
    if (p.title == '') p.title = '&nbsp;';
    if (!p.top) p.top=$(top).scrollTop() + 30;
    if (p.fixButtons) {
        var onOk = function (item, Dialog) {
                if (p.onOk) {
                    p.onOk();
                }else if (Dialog.onOk) {
                    Dialog.onOk(); //在子页面里绑定 frameElement.dialog.onOk = function () {}
                }else{
                    throw 'You should have a callback, that named onOk !'
                }
            };
        var onCancel = function (item, Dialog) {
                if (p.onCancel) {
                    p.onCancel();
                }else if (Dialog.onCancel) {
                    Dialog.onCancel(); //在子页面里绑定 frameElement.dialog.onCancel = function () {}
                }else{
                    Dialog.close();
                }
            };
        p.buttons = [{
                    text: $.ligerDefaults.DialogString.ok, onclick: onOk, type: 'ok', cls: 'l-dialog-btn-ok'
                }, {
                    text: $.ligerDefaults.DialogString.cancel, onclick: onCancel, type: 'cancel', cls: 'l-dialog-btn-no'
                }
            ];
    }
    onLoaded_funcs.push(function () {
        // 如果弹窗嵌入的iframe的body里没有.iframeBody_popup，就添加这个class
        if (!this.frame.$('body').hasClass('iframeBody_popup')) this.frame.$('body').addClass('iframeBody_popup');
    });
    if (p.autoFixHeight) {
        onLoaded_funcs.push(function () {
            // if (this.frame && this.frame.SET_popupIframeHeight) {this.frame.SET_popupIframeHeight()};
            //上面的代码改成如下 ^
            if (this.frame) this.jiframe.height(this.frame.$("html").outerHeight());
        });
        p.cls += ' autoFixHeight';
    };
    p.onLoaded = function () {
        for (var i = 0; i < onLoaded_funcs.length; i++) {
            onLoaded_funcs[i].call(this);
        };
    };
    return $.ligerDialog(p);
};
$.ligerDialog.SQalert = function (options){
    var _p={
        SQ_buttonYesText : "确定",
        SQ_showButtons : false,
        title: "提示",
        SQ_showTitle : false,
        content: "",
        SQ_timeout : 1500,
        SQ_type : null,
        cls: '',
        SQ_onBtnclick : null,
        top: null
    };
    // console.log($(window).scrollTop());
    $.extend(_p, options || {});
    var btnclick = function (item){
            _close()
            if (_p.SQ_onBtnclick && (typeof (_p.SQ_onBtnclick) == "function")){
                _p.SQ_onBtnclick(item.type);
            }
        };
    if (_p.SQ_showButtons) {
        _p.SQ_timeout=false;
        _p.cls += " hasAlertBtn "
        _p.buttons = [{ text: _p.SQ_buttonYesText, onclick: btnclick, type: 'yes' }];
    }
    _p.cls += " SQalert ";
    if (!_p.SQ_showTitle) {_p.cls += "noTitle "; _p.title="&nbsp;"}
    switch (_p.SQ_type){
        case "success":
            _p.cls += " alert_success "
            break;
        case "warning":
            _p.cls += " alert_warning "
            break;
        case "error":
            _p.cls += " alert_error "
            break;
        case "waitting":
            _p.cls += " alert_waitting "
            _p.content='<span class="loadingGif"></span> '+_p.content
            break;
    }
    p = {
        isHidden: true,
        allowClose: false,
        buttons: null
    };
    $.extend(p, _p);
    var dialog = $.ligerDialog(p);
    (function () {
        if (window == top) return;
        if(frameElement && frameElement.dialog) return;
        var topPos = 0,
            headNnav_H = top.headNnav_H ? top.headNnav_H : 82;
        if (_p.top != null) topPos = _p.top;
        else _p.top = topPos = 0.5 * ($(top).height() - headNnav_H - dialog.dialog.height()) + $(top).scrollTop() - 70;
        if (topPos < 0) _p.top = topPos = 0;
        dialog.dialog.css({top: topPos });
    })();
    if (_p.SQ_type=="waitting") return dialog;
    var $SQalertMask_El = $('<div class="l-SQalert-mask" style="display: block; position: fixed; left: 0; top: 0; width: 100%; height: 100%; background: none; overflow: hidden; z-index: 9199;"></div>')
    $("body").append($SQalertMask_El);
    var _close = function () {
        if(dialog) dialog.close();
        $SQalertMask_El.remove();
    }
    var _T = null
    if (_p.SQ_timeout && isInteger(_p.SQ_timeout) && (_T==null)) {
        _T=setTimeout(_close,_p.SQ_timeout)
    };
    $SQalertMask_El.click(function(event) {
        if (_p.SQ_showButtons) return false;
        event.preventDefault();
        event.stopPropagation();
        if(_T != null) {
            clearTimeout(_T);
            _T = null;
        };
        _close();
    });
};
$.ligerDialog.SQconfirm = function (content, title, callback){
    if (typeof (title) == "function")
    {
        callback = title;
        type = null;
    }
    var btnclick = function (item, Dialog)
    {
        Dialog.close();
        if (callback)
        {
            callback(item.type == 'ok');
        }
    };
    p = {
        cls: 'SQconfirm',
        type: 'question',
        content: content,
        top: $(top).scrollTop() + 30,
        verticalCenter: true,
        buttons: [
            {
                text: $.ligerDefaults.DialogString.yes, onclick: btnclick, type: 'ok', cls: 'l-dialog-btn-ok'
            }, {
                text: $.ligerDefaults.DialogString.no, onclick: btnclick, type: 'no', cls: 'l-dialog-btn-no'
            }
        ]
    };
    if (typeof (title) == "string" && title != "") p.title = title;
    $.extend(p, {
        showMax: false,
        showToggle: false,
        showMin: false
    });
    // return $.ligerDialog(p);
    var dialog = $.ligerDialog(p);
    (function () {
        if (window == top) return;
        if(frameElement && frameElement.dialog) return;
        var topPos = 0,
            headNnav_H = top.headNnav_H ? top.headNnav_H : 82;
        if (!p.verticalCenter) return;
        else p.top = topPos = 0.5 * ($(top).height() - headNnav_H - dialog.dialog.height()) + $(top).scrollTop() - 70;
        if (topPos < 0) p.top = topPos = 0;
        dialog.dialog.css({top: topPos });
    })();
    return dialog;
};
function clearLigerForm (formID) {
    var textField=$("#"+formID).find('.ui-textbox').not('[data-comboboxid]');
    var dateField=$("#"+formID).find('.ui-datepicker');
    var selectField=$("#"+formID).find('select');
    var comboField=$("#"+formID).find('.l-text-combobox [data-comboboxid]');
    var form = liger.get(formID);
    textField.each(function(index, el) {
        var textItem=liger.get($(this).attr('ligeruiid'));
        textItem.setValue("");
        form.hideFieldError($(this).attr('name'));
    });
    dateField.each(function(index, el) {
        var dateItem=liger.get($(this).attr('ligeruiid'));
        dateItem.setValue(null);
        form.hideFieldError($(this).attr('name'));
    });
    comboField.each(function(index, el) {
        if (!$(this).attr('ligeruiid')) return;
        var comboItem=liger.get($(this).attr('ligeruiid'));
        comboItem.clear();
        form.hideFieldError($(this).attr('name'));
    });
    selectField.each(function(index, el) {
        var selectItem=liger.get($(this).attr('ligeruiid'));
        if(selectItem.element.value!=" ") selectItem.setValue(" "); //select默认值是" "空字符串
        form.hideFieldError($(this).attr('name'));
        form.hideFieldError($(this).attr('name')+"_txt");
    });
}

function CreatUploadInputBox (options) {
    var _options={
        target: null, //css选择器，class or id | 如果没有指定target，返回组件本身，但不添加到DOM
        deletable: false,
        clearLine: false, //是否一行一个组件
        buttonText: "浏览",
        placeholder: "请选择文件",
        id: "", //如果target是多个，第一个是指定的id，其它id后面添加下标
        onDelete: null,
        onBeforeRender: null,
        onChange: null,
        finishClear: false
    };
    $.extend(true, _options, options);

    var idName="fileupload_" +new Date().getTime();
    if (_options.id) idName=_options.id;
    var fileUploadHtml=
        '<div class="fileUploadBox">\
        <span class="sq-button sq-button-hasicon fileupload-button">\
            <i class="sqBtnIco_32"></i><span class="buttonText">'+ _options.buttonText +'</span>\
            <input class="fileupload-input" id="'+ idName +'" type="file" name="'+ idName +'">\
        </span>\
        <span class="inputBox filenameBox placeholder" data-placeholder="'+_options.placeholder+'">'+ _options.placeholder +'</span>\
        <span class="sq-button-hasicon onlyicon deleteButton Hide"><i class="sqBtnIco_7"></i></span>\
        </div>';
    if (_options.target == null) {
        var $Html=$(fileUploadHtml);
        if (_options.clearLine) {
            $Html.css({
                display: 'block',
                margin: '0 2px 2px 0'
            });
        };
        _setEvents($Html);
        _setOptions($Html);
        return $Html;
    }else if (_options.target && $(_options.target) && $(_options.target).length > 0) {
        $(_options.target).each(function(index, el) {
            var $Html=$(fileUploadHtml);
            if ($(el).parents('.fileUploadBox').length>0 || $(el).find('.fileUploadBox').length>0) { //判断是否已经实例化
                $Html=_refreshHtml(el);
            }else if ($(el).is('input') && $(el).attr('type')=='file') {
                var $cloneInput=$(el).clone().show().addClass('fileupload-input');
                $Html.find('.fileupload-input').replaceWith($cloneInput);
                if ($(el).attr('id')==undefined) _addID ($Html, index, el);
                _trigger_onBeforeRender($Html);
                $(el).replaceWith($Html);
            }else if (!$(el).is('input')) {
                _addID ($Html, index, el);
                _trigger_onBeforeRender($Html);
                $(el).html($Html);
            };
            _setEvents($Html);
            _setOptions($Html);
        });
    }else{
        return;
    };
    function _setOptions(uploadBox) {
        $(uploadBox).find('[type="file"]')[0].uploadOptions = _options;
    }
    function _refreshHtml (targetEl) { //参数targetEl是原生html元素对象
        var $Html;
        if ($(targetEl).parents('.fileUploadBox').length>0) {
            $Html=$(targetEl).parents('.fileUploadBox')
        }else if ($(targetEl).find('.fileUploadBox').length>0){
            $Html=$(targetEl).find('.fileUploadBox')
        };
        if (_options.buttonText) $Html.find('.buttonText').html(_options.buttonText);
        if (_options.placeholder) $Html.find('.filenameBox').addClass('placeholder').html(_options.placeholder);
        $Html.find('.fileupload-input').val(null);
        return $Html;
    };
    function _trigger_onBeforeRender (uploadBox) {
        if (_options.onBeforeRender && $.type(_options.onBeforeRender)=='function') _options.onBeforeRender(uploadBox);
    };
    function _addID (uploadBox, index, el) {
        var ID=_options.target.slice(1) + '_' + (index + 1); //如果没有id，就用选择器和索引来指定id
        if (_options.id) {  //在有target的前提下，如果指定了id，第一项用指定id，其它id后面添加下标
            if(index == 0) ID=_options.id;
            if(index > 0) ID=_options.id + '_' + index;
        };
        uploadBox.find('.fileupload-input').attr({'id': ID, 'name': ID});
    };
    function _setEvents (uploadBox) {
        if (_options.deletable) _setDeletable (uploadBox);
        _viewUploadFileName (uploadBox);
        $(uploadBox).find('[type="file"]').on('uploaded', function(event) {
            if (_options.finishClear === true) {
                this.value = null;
                $(uploadBox).find('.filenameBox').addClass('placeholder').html(_options.placeholder);
            }
        });
    };
    function _setDeletable (uploadBox) {
        var $deleteButton=uploadBox.find('.deleteButton').removeClass('Hide');
        $deleteButton.click(function(event) {
            uploadBox.remove();
            if (_options.onDelete && $.type(_options.onDelete)=='function') _options.onDelete(uploadBox);
        });
    };
    function _viewUploadFileName (uploadBox) {
        var $uploadInput=uploadBox.find('[type=file]');
        $uploadInput.change(function(event) {
            var f=this.files;
            var temFile = null;
            var filenameBox=uploadBox.find('.filenameBox');
            if (f.length==0) {filenameBox.html(_options.placeholder).addClass('placeholder'); return;}
            for (var i = 0; i < f.length; i++) {
                temFile = f[i];
                filenameBox.html(temFile.name).removeClass('placeholder');
            };
            if (_options.onChange && $.isFunction(_options.onChange)) _options.onChange(event);
        });
    };
};
CreatUploadInputBox.clearPlaceholder = function (o) {
    var $target = $(o.target);
    if ($target.length == 0) return;
    // 清空文件
    $('.fileUploadBox', $target).find('[type="file"]').each(function(index, el) {
        $(el)[0].value = null;
    });
    // 清空placeholder
    var $filenameBox = $('.fileUploadBox', $target).find('.filenameBox');
    $filenameBox.addClass('placeholder').each(function(index, el) {
        $(el).html($(el).data('placeholder'));
    });
    // 清空fileIcon
    $('.fileUploadBox', $target).find('.fileIcon').remove();
}
function filter_autoComboboxData (key, combobox) {
    if (!combobox.initData) {combobox.initData = combobox.data};
    combobox.bind('clear', function () {
        combobox.setData(combobox.initData);
    });
    var filterRules = key ? [{
                        field: combobox.options.textField,
                        op: "like",
                        type: "text",
                        value: key
                    }] : []
    var filterFunction = $.ligerFilter.getFilterFunction(filterRules);
    var newData = [];
    for (var i = 0; i < combobox.initData.length; i++) {
        if (filterFunction(combobox.initData[i])) {
            newData[newData.length] = combobox.initData[i]
        };
    };
    combobox.setData(newData);
};
var SQ = {
    tab_onceLoad: function (ligerTab) {
        var tabid_list = ligerTab.getTabidList(ligerTab.getSelectedTabItemID());
        var flag_tabLoaded = {};
        flag_tabLoaded[ligerTab.getSelectedTabItemID()] = true;
        $(tabid_list).each(function(i, el) {
            flag_tabLoaded[tabid_list[i]] = false;
        });
        ligerTab.bind('afterSelectTabItem', function(tabid) {
            if (!flag_tabLoaded[tabid]) {
                ligerTab.reload(tabid);
                flag_tabLoaded[tabid] = true;
            };
        });
    },
    tab_dropMenu: function (options) {
        if (!options) return;
        var pageInTab = options.ligerTab,
            tabid = options.tabid,
            items = options.items;
        $('[tabid='+tabid+']').find('a').append('<span class="sqIco sqIco_downArrow dropdown_btn"></span>');
        var h = '<ul class="tabDrop" id="tabDrop_'+ tabid +'">';
        $(items).each(function(i, item) {
            var activeCls = "";
            i == 0 ? activeCls = "active" : "";
            h += '<li class="'+ activeCls +'" data-target="'+ item.target +'"><span>'+ item.text +'</span></li>'
        });
        h += '</ul>';
        var $h = $(h);
        $("body").append($h);
        $('[tabid='+tabid+'] .dropdown_btn').click(function(event) {
            event.stopPropagation();
            if ($("#tabDrop_"+tabid).is(':hidden')) {
                _hide_dropMenu();
                _show_dropMenu(tabid);
            }else{
                _hide_dropMenu();
            };
        });
        $("li", $h).click(function(event) {
            $(this).addClass('active').siblings('li').removeClass('active');
            _hide_dropMenu();
            pageInTab.selectTabItem(tabid, true);
            pageInTab.setTabItemSrc(tabid, $(this).attr('data-target'));
        });
        $(document).click(function(event) {
            _hide_dropMenu();
        });
        function _show_dropMenu (tabid) {
            var offset = $("[tabid="+tabid+"]").offset();
            $("#tabDrop_"+tabid).show().css({
                left: offset.left,
                top: offset.top + $("[tabid="+tabid+"]").height(),
                width: $("[tabid="+tabid+"]").width()
            });
            $('[tabid='+tabid+'] .dropdown_btn').removeClass('sqIco_downArrow').addClass('sqIco_downArrowActive');
        }
        function _hide_dropMenu () {
            $(".tabDrop").hide();
            $(".pageInTab .dropdown_btn").removeClass('sqIco_downArrowActive').addClass('sqIco_downArrow');
        }
    },
    setIDs_onCheckTree: function (item, checked, tree, arr) {
        var idField = tree.options.idField || "id";
        setTimeout(function () {
            var checkNodes = getCheckNodes (item,checked);
            setRESOURCE_IDs (checkNodes, checked);
        }, 1);
        function setRESOURCE_IDs (checkNodes, ischecked) {
            if (ischecked) {
                for (var i = 0; i < checkNodes.length; i++) {
                    var checkedID=checkNodes[i][idField];
                    if(arr.indexOf(checkedID)==-1) arr.push(checkedID);
                };
            } else{
                for (var i = 0; i < checkNodes.length; i++) {
                    var checkedID=checkNodes[i][idField];
                    var index=arr.indexOf(checkedID);
                    if(index>=0) arr.splice(index,1);
                };
            };
        }
        // 获取tree check或uncheck的时候,触发的所有node，包括子节点
        function getCheckNodes (checkNode, ischecked) {
            var checkNodes = [],
                ligerTree = tree;
            //如果不是联动 或 半选择，只返回当前点击的checkNode
            if (!ligerTree.options.autoCheckboxEven || ligerTree.options.enabledCompleteCheckbox) {
                checkNodes.push(checkNode);
                return checkNodes;
            }
            function _findNodes (node) {
                checkNodes.push(node);
                if (ligerTree.hasChildren(node)) {
                    for (var i = 0; i < node.children.length; i++) {
                        var childrenNode=node.children[i];
                        _findNodes (childrenNode);
                    };
                }else{
                    return;
                };
            }
            function _findParentNodes(node) {
                var parentNode = ligerTree.getParent(node),
                    parentNodeItem = ligerTree.getParentTreeItem(node);
                if (!parentNodeItem) return;
                if (!ischecked && $('>.l-body .l-checkbox-checked', parentNodeItem).length) return;
                checkNodes.unshift(parentNode);
                if ($(parentNodeItem).attr('outlinelevel') != 1) {_findParentNodes(parentNode)};
            }
            _findParentNodes(checkNode.data);
            _findNodes (checkNode.data);
            return checkNodes;
        }
    },
    dropLinks: function (html) {
        return '<div class="dropLinks"><div class="dropBtn">更多</div><div class="dropList">' + html + '</div></div>';
    },
    previewGrid_s: function (gridID) {
        var g = liger.get(gridID),
            gData = g.rows,
            preData = {};
        if (gData.length == 0) {
            $.ligerDialog.SQalert({content: "没有可预览的数据!",SQ_type: "warning"});
            return;
        };
        _getPreviewData(gData);
        _showPreview(preData);
        function _getPreviewData(gData) {
            for (var i = 0; i < gData.length; i++) {
                var o = gData[i],
                    arr = [];
                var columns = g.columns;
                for (var j = 0;j < columns.length; j++) {
                    if (columns[j].name == undefined) continue;
                    var id = g.id + (g.options.frozen ? "|2|" : "|1|") + o.__id + '|' + columns[j].__id,
                        ctext = $(document.getElementById(id)).text().replace(/;/g, ",");
                    if (ctext == '' || ctext == undefined) continue;
                    arr.push(ctext);
                };
                if (arr[0] == undefined) arr[0] = ''; //至少第一项是非undefined
                if (preData[arr[0]]) {
                    preData[arr[0]].push(arr.slice(1));
                }else{
                    preData[arr[0]] = [];
                    preData[arr[0]].push(arr.slice(1));
                };
            };
        };
        function _showPreview(preData) {
            var htm = '<div class="previewGridWrap">';
            for(var key in preData){
                htm += '<div class="dl"><div class="dt">'+ key + ':';
                htm += '</div><div class="dd"><div class="ul">';
                for (var i = 0; i < preData[key].length; i++) {
                    htm += '<div class="li">' + (i+1) + '、 ' + preData[key][i].join(',') + '。</div>';
                };
                htm += '</div></div></div>';
            };
            htm += '</div>';

            var onCancel = function (item, Dialog) {
                Dialog.hide();
            };
            $.ligerDialog.SQopen({
                width: 500,
                autoFixHeight: true,
                title : '预览',
                content: htm,
                buttons: [
                    {
                        text: "确定", onclick: onCancel, type: 'cancel'

                    }
                ]
            });
        };
    },
    validGrid: function (gridID) {
        //Grid的columns里要添加validate属性(函数)
        var g = liger.get(gridID),
            valids = [];
        for (var i = 0; i < g.rows.length; i++) {
            var row = g.rows[i];
            for (var j = 0; j < g.columns.length; j++) {
                if (!g.columns[j].validate) continue;
                var col = g.columns[j],
                    isValid = _validCell(row, col);
                valids.push(isValid);
            };
        };
        function _validCell(r, o) {
            var col_id = o.__id
                col_name = o.name;
            var $tipDOM = $(_getGridCellDOM(r, o)),
                validResult = o.validate(r[col_name]);
            if (validResult === false || typeof validResult == "string"){
                $tipDOM.addClass('error');
                if (typeof validResult == "string") {
                    $tipDOM.attr('title', validResult).grid_ligerTip();
                };
                return false;
            }else{
                $tipDOM.removeClass('error');
                return true;
            };
        };
        function _getGridCellDOM(r, o) {
            var id = g.id + (g.options.frozen ? "|2|" : "|1|") + r.__id + '|' + o.__id;
            return $(document.getElementById(id));
        };
        g.bind('beforeEdit', function(e) {
            $(_getGridCellDOM(e.record, e.column)).ligerHideTip();
        });
        g.bind('afterEdit', function(e) {
            if (!e.column.validate) return;
            _validCell(e.record, e.column);
        });
        for (var i = 0; i < valids.length; i++) {
            if (valids[i] == false) return false;
        }
    },
    imgPreview: function(src, options) {
        var winOBJ = window,
            winPos = null, //winPos ：预览显示位置， 默认当前window框架，如果是true，就在第一层iframe里显示
            popHtml = '<div class="zoomImgWrap"><div class="mask"></div><div class="imgBox">' +
                        '<img src="'+src+'">' +
                        '</div></div>';
        var o = {
            closeBtn: true,
            onClose: null
        };
        $.extend(true, o, options);

        if (typeof options == "boolean") winPos = options;
        if (o.winPos) winPos = o.winPos;
        if (typeof winPos == "boolean" && winPos && window != top) {
            winOBJ = top.frames[top.tab.getSelectedTabItemID()];
        };
        var $pop = winOBJ.$(popHtml);
        if (o.closeBtn === true) {
            $pop.append('<span class="closeBtn sqiconfont">&#xe621;</span>');
        };
        winOBJ.$('body').append($pop);
        var startPos = 0;
        if (window != top) {
            if (parent.pageInApp && winPos !== true) startPos += 48;//48是二级标签加padding的值
            if (top.mainApp && top.headNnav_H) startPos += top.headNnav_H;
        };
        $('.imgBox', $pop).css({
            'height': $(top).height() - startPos - 1,
            marginTop: window == top ? 0 : $(top).scrollTop()
        });
        $('.closeBtn', $pop).css({
            marginTop: window == top ? 0 : $(top).scrollTop()
        });
        $('.imgBox img', $pop).smartZoom({'containerClass':'zoomableContainer'});
        $('.closeBtn, .mask', $pop).on('click', function(event) {
            // $('.imgBox img', $pop).smartZoom("destroy");
            // $pop.remove();
            r.close();
            if (o.onClose && $.isFunction(o.onClose)) o.onClose();
        });
        var r = {
            close: function () {
                $('.imgBox img', $pop).smartZoom("destroy");
                $pop.remove();
            }
        };
        return r;
    },
    scanCode: function (options) { //依赖 SQ.imgPreview 方法
        var o = {
            message : "注意：扫码时请保证鼠标焦点在此输入框内。",
            href: null,
            onScan: null
        };
        $.extend(true, o, options);
        if (!o.href) return;
        // var preview = SQ.imgPreview(o.href, {closeBtn: false});
        var preview = SQ.imgPreview(o.href,{
            onClose: function () {
                r.close();
            }
        });
        var $obj = $('<div class="codeWrap"><input type="password" class="barCodeArea"><div class="noticeBox">'+o.message+'</div></div>').appendTo('body');
        $obj.css('top', window == top ? 10 : $(top).scrollTop() + 10);
        $obj.find('input').trigger('focus').on('keydown', function(event) {
            if(event.keyCode==13) {
                if ($.isFunction(o.onScan)) {
                    o.onScan(this.value);
                }else {return}
            };
        });
        var r = {
            close: function () {
                preview.close();
                $obj.remove();
            }
        };
        return r;
    },
    //弹出新window窗口展示图片，依赖sq_iviewer
    img_winopen: function (options) {
        var _srcWin = options.srcWin;
        $('[role="winOpen"]').on('click', function(event) {
            event.preventDefault();
            var imgSrc = $(event.target).attr('src'),
                imgTit = $(event.target).attr('title');
            window.__ImgSrc = imgSrc;
            window.__ImgTit = imgTit;
            window.open(_srcWin, '_blank', 'location=yes, resizable=yes, width=800, height=600, left=500, top=500');
        });
    },
    add_tabFlasher: function (options) {
        if (!options) return;
        var pageInTab = options.ligerTab,
            tabid = options.tabid,
            tip = options.tip,
            $flasher = $('<i class="flasher ico_flasher"></i>');
        if (tip) {
            $flasher.attr('title', tip);
        }
        $('.l-tab-links [tabid='+tabid+']', pageInTab.element).find('a').prepend($flasher);
        $flasher.ligerTip();
    }
};
SQ.utils = {
    currencyFormatter : function(num, precision){
        var cents, sign;
        if (!num) num = 0;
        num = num.toString().replace(/\$|\,/g, '').replace(/[a-zA-Z]+/g, '');
        if (num.indexOf('.') > -1) num = num.replace(/[0]+$/g, '');
        if (isNaN(num))
            num = 0;
        sign = (num == (num = Math.abs(num)));

        if (precision == null)
        {
            num = num.toString();
            cents = num.indexOf('.') != -1 ? num.substr(num.indexOf('.') + 1) : '';
            if (cents)
            {
                num = Math.floor(num * 1);
                num = num.toString();
            }
        }
        else
        {
            precision = parseInt(precision);
            var r = Math.pow(10, precision);
            num = Math.floor(num * r + 0.50000000001);
            cents = num % 100;
            num = Math.floor(num / r).toString();
            while (cents.toString().length < precision)
            {
                cents = "0" + cents;
            }
        }
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
            num.substring(num.length - (4 * i + 3));
        var numStr = "" + (((sign) ? '' : '-') + '' + num);
        if (cents) numStr += ('.' + cents);
        return numStr;
    },
    dataToFix : function () {
        $('[data-tofix]').each(function(index, el) {
            var Precision = $(this).data('tofix');
            $(this).toFixNumber(Precision,
                {
                    onToFix: function () {
                        top.$.ligerDialog.SQalert({SQ_type: "warning", content: "小数点后不能超过"+Precision+"位数！"});
                    }
                }
            );
        });
    }
};
SQ.regs ={
    img: /^.*\.(?:png|jpg|bmp|gif|jpeg|tiff)$/i
};
(function($){
   $.fn.setDisabled_ligerRadio = function(a){
      this.each(function(index, el) {
          var ligeruiid=$(el).attr('ligeruiid');
          if (!ligeruiid) return;
          if (a === true) {
            liger.get(ligeruiid).setDisabled();
          }else if(a === false){
            liger.get(ligeruiid).setEnabled();
          };
      });
   };
   $.fn.setDisabled_ligerTextarea = function(a){
    if (a === true) {
        this.attr('readonly', true).addClass('textarea-disabled');
    }else if(a === false){
        this.attr('readonly', false).removeClass('textarea-disabled');
    };
   };
   //grid表格内部，添加ligerTip（render的时候必须嵌套一层）
   $.fn.grid_ligerTip = function(){
        this.each(function(index, el) {
            var distanceX=0,
                gridTip_position = 'right',
                this_W=$(this).width(),
                parent_W=$(this).parent().width();
            if (this_W > parent_W) distanceX=parent_W - this_W;
            var tip_rightPosition=$(this).offset().left + $(this).width() + 170;
            if (tip_rightPosition > $(window).width()) gridTip_position = 'left';
            $(this).ligerTip({
                distanceX: distanceX + 3,
                distanceY: -3,
                auto: true,
                position: gridTip_position
            });
        });
   };
   $.fn.show_ligerComboItems = function(wrapper){ //指定items放入的容器
        var combo_Mng=this.ligerGetComboBoxManager(),
            combo_texts=combo_Mng.getText().split(';'),
            combo_texts_h='';
        for (var i = 0; i < combo_texts.length; i++) {
            combo_texts_h += '<li>' + combo_texts[i] + '</li>';
        };
        combo_texts_h = '<ul class="combo_itemList">' + combo_texts_h + '</ul>';
        if (wrapper && typeof wrapper == 'string') {
            this.parents('.l-text-wrapper').siblings(wrapper).find(".combo_itemList").remove();
            if (combo_texts.length == 1 && combo_texts[0] == "") return;
            this.parents('.l-text-wrapper').siblings(wrapper).css('display', 'block').html(combo_texts_h);
        } else{
            this.parents('.l-text-wrapper').next(".combo_itemList").remove();
            if (combo_texts.length == 1 && combo_texts[0] == "") return;
            this.parents('.l-text-wrapper').after(combo_texts_h);
        };
   };
   $.fn.add_ligerFormEditor = function(callback){ //动态添加表单元素，并返回新加元素的control
        if (this.length == 0) return;
        var that = this;
        var this_editor = null;
        var this_ligerForm=liger.get(this.parents("form").attr('ligeruiid'));
        $.each(this_ligerForm.autoEditors, function(index, el) {
            if (that.attr("name") == el.name) {
                this_editor = el;
            }
        });
        if (this_editor) return this_editor.control; //如果已经实例化，就返回它的control
        this_editor=$.ligerDefaults.Form.editorBulider.call({options: {inputWidth: 180}}, this);
        this_ligerForm.autoEditors.push(this_editor);
        if (callback && typeof callback == 'function') callback(this_editor.control);
        SetIframe_height();
        return this_editor.control;
   };
   $.fn.remove_ligerFormEditor = function(){ //单独制定删除liger表单对象，包括HTML元素
        if (this.length == 0) return;
        var that = this;
        var this_form = this.parents("form");
        var this_ligerForm=liger.get(this_form.attr('ligeruiid'));
        var editors = this_ligerForm.autoEditors;
        for (var i = 0; i < editors.length; i++) {
            if (this.attr('name') == editors[i].name) {
                editors[i].control.destroy();
                _removeElements(editors[i]);
                editors.splice(i, 1);
                i--;
            };
        };
        function _removeElements (editor) {
            switch(editor.control.type){
                case "ComboBox":
                    if (that.css('display') == 'none') {
                        that.next('.l-text-wrapper').remove();
                        that.remove();
                    }else if(that.prop('readonly')){
                        that.parents('.l-text-wrapper').remove();
                    };
                  break;
                case "Radio":
                    that.parents('.l-radio-wrapper').remove();
                    break;
                case "DateEditor":
                    that.parents('.l-text-wrapper').remove();
                case "TextBox":
                    that.parents('.l-text').remove();
                    break;
                default:
                  that.remove();
            }
        }
   };
   $.fn.check_ligerFormEditor = function(){ //1，新增的元素liger实例化；2，删除的元素从autoEditors数组中移除
        if (this.length == 0) return;
        var that = this;
        var this_ligerForm=liger.get(this.attr('ligeruiid'));
        var editors = this_ligerForm.autoEditors;
        for (var i = 0; i < editors.length; i++) { //清理autoEditors中的ligerForm对象，并destroy
            (function () {
                var $editor = that.find('[name='+editors[i].name+']');
                if ($editor.filter('[ligeruiid]').hasClass('newEditor')) { //初始化没能清除".newEditor"的case
                    $editor.removeClass('newEditor');
                };
                if ($editor.length == 0 || $editor.not('[ligeruiid]').hasClass('newEditor')) { //无对应元素 || 重新加载后重复的组件（样式没刷新）的case
                    if(editors[i].control.type) editors[i].control.destroy();
                    editors.splice(i, 1);
                    i--;
                };
            })();
        };
        this.find("input, select, textarea").each(function(index, el) { //当有新的还没实例化成为ligerForm对象的，全部实例化
            if ($(el).hasClass('newEditor') && !_isLigerFormEditor(el)) {
                $(el).removeClass('newEditor').add_ligerFormEditor();
            }
        });
        SQ.utils.dataToFix();
        function _isLigerFormEditor (el) {
            var result = false;
            for (var i = 0; i < editors.length; i++) {
                if ($(el).attr('name') == editors[i].name) result = true;
            };
            return result;
        };
   };
    $.fn.pageInSideLink = function(o){
        if ($('li.active', this).length != 1) {
            if (o && o.currentNav) {
                $('#'+o.currentNav).addClass('active');
            }else{
                $('li:first-child', this).addClass('active');
            };
        };
        $('li', this).each(function(index, el) {
            $(el).on('click', function(event) {
                var src = $(this).data('src');
                if (!src) return;
                if (parent.pageInApp && parent.pageInApp.pageInTab) {
                    var curTabID = parent.pageInApp.pageInTab.getSelectedTabItemID();
                    parent.pageInApp.pageInTab.setTabItemSrc(curTabID, src);
                }else if(parent.mainApp && parent.mainApp.parentTab){
                    var curTabID = parent.mainApp.parentTab.getSelectedTabItemID();
                    parent.mainApp.parentTab.setTabItemSrc(curTabID, src);
                };
            });
        });
    };
    //小数点后超过指定长度时，限制输入
    $.fn.toFixNumber = function (Precision, options) {
        var precision = Precision ? Precision : 2;
        var p = {
            onToFix: function () {
                // alert('小数点后面最多'+ precision +'位！');
            }
        };
        $.extend(true, p, options);
        $(this).bind('keyup change', function(event) {
            var value = $(this).val();
            var _reg_toFix  = new RegExp('(\\.[0-9]{'+ (precision+1) +'})'),
                _reg_toFix2 = new RegExp('(^[0-9]*\\.[0-9]{'+ precision +'})([0-9]*)$');
            if (_reg_toFix.test(value)) {
                if (p.onToFix && (typeof p.onToFix == "function")) p.onToFix();
                $(this).val(value.replace(_reg_toFix2, "$1"));
            }
        });
    };
    $.fn.setFull_height = function (diff_height) {
        var this_offsetTop = $(this).offset().top,
            diff_H = diff_height ? diff_height : 0;
        $(this).height($(window).height() - this_offsetTop - 30 + diff_H);
    };
    $.fn.afterUploadFile = function (options) {
        var o = {
            filenameField: 'fileNm',
            filePathField: 'filePath',
            files_DATA: null,
            multi: false,
            onDelete: null
        };
        $.extend(true, o, options);
        if (!o.files_DATA || o.files_DATA.length == 0) return;
        var that = this,
            DATA = o.files_DATA;
        if (o.multi) {
            // 单个组件 多个上传时
            var fileInput = this[0];
            var $filesList;
            setTimeout(function () {
                var $fileBtn = $(fileInput).parents('.fileupload-button');
                if ($fileBtn.prev('.FilesList').length > 0) {
                    $filesList = $fileBtn.prev('.FilesList')
                } else {
                    $filesList = $('<ul class="FilesList"></ul>');
                    $fileBtn.before($filesList);
                };
                for (var i = 0; i < DATA.length; i++) {
                    var fileName = DATA[i][o.filenameField];
                    var $fileItem = $('<li><span class="count"></span><span class="fineName">'+fileName+'</span></li>').appendTo($filesList);
                    $fileItem.data('filedata', DATA[i]);
                    _setCount();
                    _setIcons($fileItem, DATA[i][o.filenameField], DATA[i][o.filePathField]);
                };
                SetIframe_height();
                fileInput.value = null;
            }, 100);
            function _setCount() {
                $filesList.find('li .count').each(function(index, el) {
                    $(el).html(index + 1 + ')&nbsp;&nbsp;');
                });
            }
            function _setIcons(filebox, filename, filePath) {
                var iconClass = SQ.regs.img.test(filename) ? 'sqBtnIco_52' : 'sqBtnIco_8';
                var $icons = $('<div class="icons"><a class="fileIcon" href="'+filePath+'"><span class="sq-button-hasicon onlyicon"><i class="'+ iconClass +'"></i></a></span><span class="sq-button-hasicon onlyicon deleteButton"><i class="sqBtnIco_7"></i></span></div>').appendTo(filebox);
                if (SQ.regs.img.test(filename)) {
                    $('.fileIcon', $icons).click(function(event) {
                        event.preventDefault();
                        SQ.imgPreview($(this).attr('href'), true);
                    });
                }else{
                    $('.fileIcon', $icons).click(function(event) {
                        event.preventDefault();
                        window.open($(this).attr('href'));
                    });
                };
                $('.deleteButton', $icons).click(function(event) {
                    var $li = $(this).parents('li');
                    var fileData = $li.data('filedata');
                    if ($.isFunction(o.onDelete)) {
                        o.onDelete(fileData, __removeFile);
                    };
                    function __removeFile() {
                        $li.remove();
                        _setCount();
                    };
                });
            };
        } else {
            // 单个组件单个上传时
            setTimeout(function () {
                //需要等上传插件还原input，因此setTimeout
                var $fileBox = that.parents('.fileUploadBox');
                var fileName = that[0].files[0] && that[0].files[0].name;
                if (!fileName) return;
                if ($.isArray(DATA)) {
                    for (var i = 0; i < DATA.length; i++) {
                        var fileName_D = DATA[i].fileNm;
                        if (fileName == fileName_D) {
                            _addToIcon($fileBox, DATA[i][o.filenameField], DATA[i][o.filePathField]);
                        };
                    };
                } else if ($.isPlainObject(DATA)) {
                     _addToIcon($fileBox, DATA[o.filenameField], DATA[o.filePathField]);
                }
            }, 100);
            function _addToIcon(filebox, filename, filePath) {
                var iconClass = SQ.regs.img.test(filename) ? 'sqBtnIco_52' : 'sqBtnIco_8';
                filebox.find('.fileIcon').remove();
                var $fileIcon = $('<a class="fileIcon" href="'+filePath+'"><span class="sq-button-hasicon onlyicon"><i class="'+ iconClass +'"></i></span></a>').appendTo(filebox);
                if (SQ.regs.img.test(filename)) {
                    $fileIcon.click(function(event) {
                        event.preventDefault();
                        SQ.imgPreview($(this).attr('href'), true);
                    });
                }else{
                    $fileIcon.click(function(event) {
                        event.preventDefault();
                        window.open($(this).attr('href'));
                    });
                };
            };
        };
    };
    $.fn.remove_afterUploadIcon = function () {
        this.parents('.fileUploadBox').find('.fileIcon').remove();
    };
    //合并ligerGrid指定列同名单元格
    $.fn.rowspan_S = function (colname, gridid) {
        var colIdx,
            Grid = liger.get(this[0].id)
            tableBody = this.find('.l-grid-body-table tbody');
        console.log(Grid);
        for (var i = 0, n = Grid.columns.length; i < n; i++) {
            if (Grid.columns[i]["columnname"] == colname) {
                // colIdx = i - 1 < 1 ? 0 : i - 1;
                colIdx = i;
                if (Grid.options.frozen) {
                    var frozenTdLength = Grid.gridview1.find('.l-grid-body-table tr:first-child td').length;
                    colIdx = i - frozenTdLength; //To do : columns设置里面有frozen:true会出bug
                };
                break;
            }
        };
        return tableBody.each(function () {
            var that;
            $('tr', this).each(function (row) {
                $('td:eq(' + colIdx + ')', this).filter(':visible').each(function (col) {
                    if (that != null && $(this).html() == $(that).html()) {
                        rowspan = $(that).attr("rowSpan");
                        if (rowspan == undefined) {
                            $(that).attr("rowSpan", 1);
                            rowspan = $(that).attr("rowSpan");
                        }
                        rowspan = Number(rowspan) + 1;
                        $(that).attr("rowSpan", rowspan);
                        $(this).hide();
                    } else {
                        that = this;
                    }
                });
            });
        });
    };
    $.fn.rowspan = function (colname, gridid) {
        var colID,
            Grid = liger.get(this[0].id)
            tableBody = this.find('.l-grid-body-table tbody');
        for (var i = 0, n = Grid.columns.length; i < n; i++) {
            if (Grid.columns[i]["columnname"] == colname) {
                colID = Grid.columns[i].__id;
                break;
            }
        };
        return tableBody.each(function () {
            var that;
            $('tr', this).each(function (row) {
                $('td[id$='+colID+']',this).each(function (col) {
                    if (that != null && $(this).html() == $(that).html()) {
                        rowspan = $(that).attr("rowSpan");
                        if (rowspan == undefined) {
                            $(that).attr("rowSpan", 1);
                            rowspan = $(that).attr("rowSpan");
                        }
                        rowspan = Number(rowspan) + 1;
                        $(that).attr("rowSpan", rowspan);
                        $(this).empty().hide();
                    } else {
                        that = this;
                    }
                });
            });
        });
    };
})(jQuery);

//添加ligerui组件的方法
(function ($) {
    $.ligerui.controls.Tree.prototype.getCheckedDataBy = function (parm) {
        var g = this, p = this.options;
        if (!this.options.checkbox) return null;
        var checkedData = g.getCheckedData(),
            values = [];
        for (var i = 0; i < checkedData.length; i++) {
            values.push(checkedData[i][parm]);
        };
        return values;
    }
})(jQuery);
var AjaxUtils = function() {};

//POST AJAX 要有回调
AjaxUtils.ajaxPost = function(_url, _params, callback, showTip){
	var wait_dialog;
	if(false != showTip){
		wait_dialog=UIUtils.alertWaiting(LogUtils.LOG_CMM_DATA_LOADING, null);
	}
	$.ajax({
		type: 'post',
		dataType:'json',
		data:_params,
		url: _url,
		success:function(msg){
			if(false != showTip){
				wait_dialog.close(); 
			}
			callback(msg);
		}
	});
}


//GET AJAX 要有回调
AjaxUtils.ajaxGet = function(_url, _params, callback, showTip){
	var wait_dialog;
	if(false != showTip){
		wait_dialog=UIUtils.alertWaiting(LogUtils.LOG_CMM_DATA_LOADING, null);
	}
	$.ajax({
		type: 'get',
		dataType:'json',
		data:_params,
		url: _url,
		success:function(msg){
			if(false != showTip){
				wait_dialog.close(); 
			}
			callback(msg);
		}
	});
}
/**
 * 集合工具类
 */
CollectionUtils = {
	
};

/**
 * 判断对象是否为数组
 */
CollectionUtils.isArray = function(obj) {
	return obj instanceof Array;
};

/**
 * 判断对象是否为数组
 */
CollectionUtils.isEmpty = function(obj) {
	if(obj.length <= 0){
		return true;
	}
	return false;
};

/**
 * 判断字符串不为空
 */
CollectionUtils.isNotEmpty = function(obj) {
	return !CollectionUtils.isEmpty(obj);
};


/**
 * Cookie工具类
 */
CookieUtils = {
};

/**
 * 移除Cookie
 */
CookieUtils.remote = function(name)
{
	$.cookie(name, "", -1);
};


/**
 * 日期工具类
 */
DateUtils = {
};

/**
 * 格式化串
 */
DateUtils.YYYY_MM_DDHHMMSS = "yyyy-MM-dd hh:mm:ss";

DateUtils.YYYY_MM_DD = "yyyy-MM-dd";

/**
 * 格式化日期
 */
DateUtils.formatDate = function(date,format){
  var paddNum = function(num){
    num += "";
    return num.replace(/^(\d)$/,"0$1");
  }
  //指定格式字符
  var cfg = {
     yyyy : date.getFullYear() //年 : 4位
    ,yy : date.getFullYear().toString().substring(2)//年 : 2位
    ,M  : paddNum(date.getMonth() + 1)  //月 : 如果1位的时候不补0
    ,MM : paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
    ,d  : paddNum(date.getDate())   //日 : 如果1位的时候不补0
    ,dd : paddNum(date.getDate())//日 : 如果1位的时候补0
    ,hh : paddNum(date.getHours())  //时
    ,mm : paddNum(date.getMinutes()) //分
    ,ss : paddNum(date.getSeconds()) //秒
  }
  format || (format = "yyyy-MM-dd hh:mm:ss");
  return format.replace(/([a-z])(\1)*/ig,function(m){return cfg[m];});
} 

/* 
* 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时：分钟：秒 
* 其中，年月日为全格式，例如 ： 2016-4-12 01:00:00 
* 返回精度为：秒,分,小时,天,年
* 使用方式：
* var testDate = new Date();
* var testStr = DateUtils.formatDate(testDate,DateUtils.YYYY_MM_DDHHMMSS);
* var result = GetDateDiff("2010-02-26 16:00:00", testStr, "day");
*/
DateUtils.getDateDiff = function(startTime, endTime, diffType) {
    startTime = startTime.replace(/\-/g, "/");
    endTime = endTime.replace(/\-/g, "/");
    //将计算间隔类性字符转换为小写
    diffType = diffType.toLowerCase();
    var sTime = new Date(startTime);//开始时间
    var eTime = new Date(endTime);//结束时间
    //作为除数的数字
    var divNum = 1;
    switch (diffType) {
        case "second":
            divNum = 1000;
            break;
        case "minute":
            divNum = 1000 * 60;
            break;
        case "hour":
            divNum = 1000 * 3600;
            break;
        case "day":
            divNum = 1000 * 3600 * 24;
            break;
        case "year":
            divNum = 1000 * 3600 * 24 * 365;
            break;
        default:
            break;
    }
    return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
}



//格式化时间 value 格式为可被 new Date识别串
DateUtils.formatDateToString = function(value, format){
	var dateStr = "";
	if(null != value){
		var date = new Date(value);
		dateStr = DateUtils.formatDate(date, format);
	}
	return dateStr;
}
function HashMap(){  
    //定义长度  
    var length = 0;  
    //创建一个对象  
    var obj = new Object();  
  
    /** 
    * 判断Map是否为空 
    */  
    this.isEmpty = function(){  
        return length == 0;  
    };  
  
    /** 
    * 判断对象中是否包含给定Key 
    */  
    this.containsKey=function(key){  
        return (key in obj);  
    };  
  
    /** 
    * 判断对象中是否包含给定的Value 
    */  
    this.containsValue=function(value){  
        for(var key in obj){  
            if(obj[key] == value){  
                return true;  
            }  
        }  
        return false;  
    };  
  
    /** 
    *向map中添加数据 
    */  
    this.put=function(key,value){  
        if(!this.containsKey(key)){  
            length++;  
        }  
        obj[key] = value;  
    };  
  
    /** 
    * 根据给定的Key获得Value 
    */  
    this.get=function(key){  
        return this.containsKey(key)?obj[key]:null;  
    };  
  
    /** 
    * 根据给定的Key删除一个值 
    */  
    this.remove=function(key){  
        if(this.containsKey(key)&&(delete obj[key])){  
            length--;  
        }  
    };  
  
    /** 
    * 获得Map中的所有Value 
    */  
    this.values=function(){  
        var _values= new Array();  
        for(var key in obj){  
            _values.push(obj[key]);  
        }  
        return _values;  
    };  
  
    /** 
    * 获得Map中的所有Key 
    */  
    this.keySet=function(){  
        var _keys = new Array();  
        for(var key in obj){  
            _keys.push(key);  
        }  
        return _keys;  
    };  
  
    /** 
    * 获得Map的长度 
    */  
    this.size = function(){  
        return length;  
    };  
  
    /** 
    * 清空Map 
    */  
    this.clear = function(){  
        length = 0;  
        obj = new Object();  
    };  
}
/**
 * 日志工具类,前端提示信息工具常量类
 */
LogUtils = {};

//=============通用提示============
LogUtils.LOG_CMM_ADD_SUCC = "新增成功!";
LogUtils.LOG_CMM_ADD_FAIL = "新增失败!";
LogUtils.LOG_CMM_UPDATE_SUCC = "修改成功!";
LogUtils.LOG_CMM_UPDATE_FAIL = "修改失败!";
LogUtils.LOG_CMM_DELETE_SUCC = "删除成功!";
LogUtils.LOG_CMM_DELETE_FAIL = "删除失败!";
LogUtils.LOG_CMM_OPERATE_SUCC = "操作成功!";
LogUtils.LOG_CMM_OPERATE_FAIL = "操作失败!";
LogUtils.LOG_CMM_UL_SUCC = "上传成功!";
LogUtils.LOG_CMM_UL_FAIL = "上传失败!";
LogUtils.LOG_CMM_DELETE_CONFIRM = "是否确认删除?";
LogUtils.LOG_CMM_BACK_CONFIRM = "是否确认恢复?";
LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO = "您有必填项信息未维护！";
LogUtils.LOG_CMM_MUST_FIX_SIGNREM_LENGTH = "备注信息超出限制长度！";
//LogUtils.LOG_CMM_SUBMIT_CONFIRM_ITEM_INFO = "您有信息未提交/保存，是否确认离开当前页面？";
//LogUtils.LOG_CMM_SUBMIT_CONFIRM_ITEM_INFO_BTN_SAVE = "去提交/保存";
//LogUtils.LOG_CMM_SUBMIT_CONFIRM_ITEM_INFO_BTN_LEAVE = "离开";
LogUtils.LOG_CMM_SUBMIT_CONFIRM_CONTENT_001 = "确定要提交吗?";
LogUtils.LOG_CMM_BTN_CLOSE = "关闭";//按钮显示
LogUtils.LOG_CMM_BTN_SAVE = "保存";//按钮显示
LogUtils.LOG_CMM_BTN_OK = "确定";//按钮显示
LogUtils.LOG_CMM_BTN_CANCEL = "取消";//按钮显示
LogUtils.LOG_CMM_LOADING = "正在努力加载中,请稍等片刻...";
LogUtils.LOG_CMM_DATA_LOADING = "数据处理中,请稍后...";
LogUtils.LOG_CMM_DISABLE_CONFIRM = "是否确认禁用?";
LogUtils.LOG_CMM_ENABLE_CONFIRM = "是否确认启用?";
LogUtils.LOG_CMM_SELECT_ONLY_A_ROW = "请选择一条数据!";
LogUtils.LOG_CMM_SELECT_MORE_ROW = "请至少选择一条数据!";
LogUtils.LOG_CMM_GRID_BTN_DELETE = "删除";//GRID 中操作列中显示
LogUtils.LOG_CMM_GRID_BTN_ENABLE = "启用";//GRID 中操作列中显示
LogUtils.LOG_CMM_GRID_BTN_DISABLE = "禁用";//GRID 中操作列中显示
LogUtils.LOG_CMM_VALID_PASS = "验证通过";
LogUtils.LOG_CMM_VALID_FAIL = "验证未通过";
LogUtils.LOG_CMM_ENABLED_STATUS = "已经启用无需再次启用！";
LogUtils.LOG_CMM_DISABLED_STATUS = "已经禁用无需再次禁用！";
LogUtils.LOG_CMM_MODIFY_AUTH_NO = "您无权修改记录！";
LogUtils.LOG_CMM_GRID_BTN_ZF = "作废";//GRID 中操作列中显示
LogUtils.LOG_CMM_GRID_BTN_MODIFY = "修改";//GRID 中操作列中显示
LogUtils.LOG_CMM_GRID_BTN_BACK = "恢复";//GRID 中操作列中显示
LogUtils.LOG_CMM_GRID_BTN_VALID = "验证";//GRID 中操作列中显示
//=============客户模块提示=LogUtils.LOG_CUST_...===========
LogUtils.LOG_CUST_CONFIRM_HERE_HAS_INFO = "请确定客户信息存在后在操作！";
LogUtils.LOG_CUST_SWAP_TAB_BASE_INFO = "确定切换吗？切换后数据将丢失！";
LogUtils.LOG_CUST_ID_NOT_EMPTY = "客户ID不存在！";
LogUtils.LOG_CUST_ID_CARD_NOT_EMPTY = "客户证件号码不能为空！";
LogUtils.LOG_CUST_CORP_NAME_NOT_EMPTY = "法定代表人名称不能为空！";
LogUtils.LOG_CUST_CORP_ID_CARD_VALID_NO_PASS = "法人身份证验证未通过！";
LogUtils.LOG_CUST_NAME_NOT_EMPTY = "客户名称不能为空！";
LogUtils.LOG_CUST_ID_CARD_VALID_NO_PASS = "身份证验证未通过！";
LogUtils.LOG_CUST_INFO_EXIST = "客户信息已经存在,是否带入已有信息！";
LogUtils.LOG_CUST_LOCK_OPEN_SUCC = "解锁成功！";
LogUtils.LOG_CUST_SELECT_OTHER_VALUE = "其他";
LogUtils.LOG_CUST_NO_VALID_CARD="没有权限验证中国邮政储蓄代扣卡!";
LogUtils.LOG_CUST_STOP_USED_ZF ="确定要作废吗!";
LogUtils.LOG_CUST_STOP_USED_BKP ="确定不开票吗!";
LogUtils.LOG_CUST_APPLY_INVOICE_NEW ="发起流程";
LogUtils.LOG_CUST_GRID_INVOICE_NO_NEED ="不开票";//GRID 中操作列中显示
LogUtils.LOG_CUST_GRID_IS_DEDUCT ="是否代扣卡";//GRID 中操作列中显示
LogUtils.LOG_CUST_GRID_CREAT_PROJECT ="立项申请";//GRID 中操作列中显示
//=============产品模块提示============
LogUtils.LOG_PRD_CONFIRM_MFR_INFO_EXIST = "请确认厂商基本信息已经维护！";
LogUtils.LOG_PRD_CONFIRM_SPL_INFO_EXIST = "请确认供应商基本信息已经维护！";
LogUtils.LOG_PRD_AUDITOR_STATUS = "审核中";
LogUtils.LOG_PRD_APPROVED_STATUS = "审核通过";
LogUtils.LOG_PRD_AUDITOR_UPDATE = "正在审核中,不允许修改！";
LogUtils.LOG_PRD_APPROVED_UPDATE = "已经审核通过,请发起变更流程！";
LogUtils.LOG_PRD_AUDITOR_DEL = "正在审核中,不允许删除！";
LogUtils.LOG_PRD_APPROVED_DEL = "已经审核通过,不允许删除！";
LogUtils.LOG_PRD_CHECK_PRD_TYPE = "请选择最下一级产品类型！";
LogUtils.LOG_PRD_CHECK_FARM_BU = "农机事业部不能与其他事业部多选！";




//=============流程模块提示=LogUtils.LOG_FLOW_...===========
LogUtils.LOG_FLOW_PERSON_ALWAYS_HERE = "已添加！";
LogUtils.LOG_FLOW_NEXT_TASK_OPERATOR = " 下一节点操作人：";
LogUtils.LOG_FLOW_GRID_BTN_SETTING = "设置流程";
LogUtils.LOG_FLOW_GRID_BTN_HISTORY = "历史版本";
LogUtils.LOG_FLOW_GRID_BTN_SETTING_PROCNO = "配置";
LogUtils.LOG_FLOW_CONFIRM_START = "确定要发起流程吗?";
LogUtils.LOG_FLOW_CONFIRM_CHANGE = "确定要发起变更流程吗?";
LogUtils.LOG_FLOW_EXE_ROW = "处理";
LogUtils.LOG_FLOW_PRIVATE_ROW = "签收";
//=============登录模块提示============
LogUtils.LOG_USER_LOGIN_INPUT_USER_NAME = "请输入用户名!";
LogUtils.LOG_FLOW_LOGIN_INPUT_USER_PWD = "请输入密码!";
LogUtils.LOG_FLOW_LOGIN_WAITING = "登陆中请稍候......";
//=============登录模块提示============

//=============权限模块提示============
LogUtils.LOG_SYS_ORG_INSIDE_FORBID_HANDLE = "系统内置数据请勿操作！";
LogUtils.LOG_SYS_ORG_SELECT_BEFORE = "请先选择！";
LogUtils.LOG_SYS_ORG_SELECT_ROLE = "请选择角色！";
LogUtils.LOG_SYS_ORG_SELECT_ROLE_ONLY = "请选择唯一的角色！";
LogUtils.LOG_SYS_ORG_SELECT_EXTEND_ROLE = "请选择继承角色！";
LogUtils.LOG_SYS_ORG_NOT_SELECT_SAME_ROLE = "不要选择同样的角色！";
LogUtils.LOG_SYS_ORG_ROLE_NAME_NULL = "角色名称不能为空！";
LogUtils.LOG_SYS_ORG_USR_NOT_EXIST = "查无此人！";
LogUtils.LOG_SYS_ORG_SELECT_RESET_DATA = "请选择要重置的数据！";
LogUtils.LOG_ORD_RESET_CONFIRM = "是否确认重置?";
LogUtils.LOG_SYS_ORG_SELECT_ORG = "请选择组织架构！";
LogUtils.LOG_SYS_ORG_SELECT_USR = "请选择用户！";
LogUtils.LOG_CMM_ADD_USR_SUCC = "新增用户成功！";

//=============保险模块提示=LogUtils.LOG_CUST_...===========
LogUtils.LOG_INS_CONFIRM_HERE_HAS_INFO = "请先保存支公司信息！";



//=============项目模块提示=LogUtils.LOG_PRJ_...===========
LogUtils.LOG_PRJ__PRD_SELECT_BEFORE="请先保存项目基本信息！";
LogUtils.LOG_PRJ_CST_SELECT_BEFORE="请请选择担保人！";

//=============缓存模块提示=LogUtils.LOG_CACHE_...===========
LogUtils.LOG_CACHE_REFRENCH_ALL="刷新全部缓存时间较长,确定刷新吗?";

/**
 * 数字工具类
 */
NumberUtils = {
};

/**
 * 检查是否为正数,带浮点
 */
NumberUtils.isUnsignedNumeric = function(a) {
	var reg = /^\d+(.\d+)?$/;
	return reg.test(a);
};


/**
 * 检查是否为正整数
 */
NumberUtils.isUnsignedInteger = function(a) {
	var reg = /^\d*$/;
	return reg.test(a);
};

NumberUtils.mul = function( val1, val2){
	var num1 = parseFloat(val1);
	var num2 = parseFloat(val2);
    return (num1*num2).toFixed(2);
}

/**
 * 正则工具类
 */
RegexUtils = {
};

/*
 * 4到20个字符，字母，汉字，数字，下划线的组合，不能使用纯数字
 */
var loginNameReg = /^(?![0-9]+$)\w{4,20}$/;
/*
 * 邮箱
 */
var mailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
/*
 * 字母，数字，符号，6到20个字符
 */
var pswReg= /^((?=.*[a-z])|(?=.*\d)|(?=.*[~!@#$%^&*()])|(?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[~!@#$%^&*()])|(?=.*\d)(?=.*[~!@#$%^&*()]))[a-z\d~!@#$%^&*()]{6,20}$/;
/*
 * 身份证
 */
var personCidReg= /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
/*
 * 手机号码
 */
var phoneNumberReg= /^1[3|4|5|7|8][0-9]\d{8}$/;

/**
 * 验证身份证号码
 */
RegexUtils.isIDCard = function(val) {
	return personCidReg.test(val);
};


/**
 * 字符串工具类
 */
StringUtils = {
};

/**
 * 判断字符是否为空
 */
StringUtils.isEmpty = function(val) {
	val = $.trim(val);
	if (val == '' || val == null || val == undefined) {
 		return true;
 	}
	return false;
};

/**
 * 判断字符串不为空
 */
StringUtils.isNotEmpty = function(val) {
	return !StringUtils.isEmpty(val);
};


var UIUtils = function() {};

//成功提示
UIUtils.alertSuccess = function(msg){
	 $.ligerDialog.SQalert({content:msg, SQ_type: "success"});
}
//错误提示
UIUtils.alertError = function(msg){
	//$.ligerDialog.SQalert({content:msg, SQ_type: "error"});
	 $.ligerDialog.SQalert({
         content: msg,
         SQ_type: "error",
         SQ_showButtons: true,
         SQ_onBtnclick: function (item, Dialog) {
             //console.log(item, Dialog);
         },
     });
}
//警告提示
UIUtils.alertWarning = function(msg){
	$.ligerDialog.SQalert({content: msg, SQ_type: "warning" });
}


//成功提示-有一个确定按钮 单击后关闭
UIUtils.alertSuccessHold1 = function(msg){
	 $.ligerDialog.SQalert({content:msg, SQ_showButtons: true,SQ_type: "success"});
}
//错误提示-有一个确定按钮 单击后关闭
UIUtils.alertErrorHold1 = function(msg){
	$.ligerDialog.SQalert({content:msg, SQ_showButtons: true,SQ_type: "error"});
}
//警告提示-有一个确定按钮 单击后关闭
UIUtils.alertWarningHold1 = function(msg){
	$.ligerDialog.SQalert({content: msg, SQ_showButtons: true,SQ_type: "warning" });
}

//等待提示
UIUtils.alertWaiting = function(info, callback){
	var wait_dialog = $.ligerDialog.SQalert({content: info, SQ_type: "waitting",onClose: function () {
		if (typeof(callback) == 'function') {
			callback();
		};
	}});
	return wait_dialog;
}

//GRID列提示
UIUtils.showColumnTip = function(value){
	if(StringUtils.isEmpty(value)){
	     value = ""; 
	}
	var h='<span class="gridTip" title="'+ value +'">'+ value +'</span>'
   return h;
}

/**
 * 信审常量类
 */
AuditConstant={};

//台账类型
AuditConstant.AUD_BSC_BOOK_TYP_CD = "1";//信审基础台账
AuditConstant.AUD_CORE_PRC_BOOK_TYP_CD = "2";//核价基础台账
AuditConstant.AUD_REJECT_BOOK_TYP_CD = "4";//信审驳回台账
AuditConstant.AUD_LOAN_BOOK_TYP_CD = "3";//放款基础台账

//流程信审节点附加信息 产品列表配置参数
AuditConstant.AUD_PRJ_PRD_LIST_PARAM_FOR_TK = "001";//卡车列表配置参数
AuditConstant.AUD_PRJ_PRD_LIST_PARAM_FOR_CAR = "002";//乘用车列表配置参数
AuditConstant.AUD_PRJ_PRD_LIST_PARAM_FOR_BUS = "003";//客车列表配置参数
AuditConstant.AUD_PRJ_PRD_LIST_PARAM_FOR_FARM = "004";//农机产品列表配置参数

//回访类型
AuditConstant.AUD_VISIT_TYP_CD_TEN = "1";//承租人回访
AuditConstant.AUD_VISIT_TYP_CD_GUART = "2";//担保人/紧急联系人回访
AuditConstant.AUD_VISIT_TYP_CD_FLOW = "3";//后续回访

//信审驳回意见类型
AuditConstant.SYS_FLOW_REJ_RSN_TYP_CD_PRJ = "001";//立项驳回
AuditConstant.SYS_FLOW_REJ_RSN_TYP_CD_LOAN = "002";//放款驳回
AuditConstant.SYS_FLOW_REJ_RSN_PID = 0;//一级父ID

//放款通过意见类型
AuditConstant.AUD_PAY_OPN_TYP_CD_CONTRACT = "1";//合同
AuditConstant.AUD_PAY_OPN_TYP_CD_MORTGAGE = "2";//抵押


/**
 * 流程常量类
 */
CapConstant = {};
//付款方式为网银
CapConstant.CAP_PAY_WAY_CD_E_BANK = "3";

/**
 * 公共常量类
 */
CommonConstant = {};

//=============通用提示============
CommonConstant.C_DEMO_CODE = "D001";
//=============审核状态============
CommonConstant.C_AUD_NO_HAPPEN_CODE = "0";//待提交
CommonConstant.C_AUD_ADNWAY_CODE = "1";//审核中
CommonConstant.C_AUD_PASS_CODE = "2";//审核通过
CommonConstant.C_AUD_NO_PASS_CODE = "3";//审核不通过
CommonConstant.C_AUD_CHANGEADNWAY_CODE = "99";//变更审核中
CommonConstant.C_AUD_REJECT_CODE = "4";//驳回呈报人
//=============是否状态============
CommonConstant.C_YN_Y = "1";//是否标识-是
CommonConstant.C_YN_N = "0";//是否标识-否
CommonConstant.C_YN_Y_1 = 1;//是否标识-是
CommonConstant.C_YN_N_0 = 0;//是否标识-否
CommonConstant.C_YN_Y_NM = "是";//是否标识-是
CommonConstant.C_YN_N_NM = "否";//是否标识-否
//=============流程============
CommonConstant.C_P_INSTANCEID_NOT_HERE = "流程实例不存在!";
/**
 * 客户常量类
 */
CustomerConstant = {};
//自然人
CustomerConstant.CST_TYPE_NP_CD = 1;
//法人
CustomerConstant.CST_TYPE_CORP_CD = 2;
//客户关系担保人类型值
CustomerConstant.CST_RL_TYPE_DBR_CD = 2;
//代扣卡代码-邮储
CustomerConstant.CST_BK_CD_POST = "POST";
//票据状态-正常
CustomerConstant.CODE_PRJ_BILL_STS_CD_1 = "1";
//票据状态-作废
CustomerConstant.CODE_PRJ_BILL_STS_CD_2 = "2";
//开票人员使用删除后状态为2
CustomerConstant.CODE_PRJ_BILL_R_IS_DEL_2 = "2";
//已婚
CustomerConstant.CST_MAR_STS_CD_2 = "3"
//离异
CustomerConstant.CST_MAR_STS_CD_3 = "2"
//初婚
CustomerConstant.CST_MAR_STS_CD_first = "21"
//再婚
CustomerConstant.CST_MAR_STS_CD_agian = "22"
//复婚
CustomerConstant.CST_MAR_STS_CD_back = "23"

/**
 * DEMO常量类
 * 各个模块自定义命名常量文件名称,格式：xxxConstant.js
 */
DemoConstant = {};

//=============通用提示============
DemoConstant.C_DEMO_CODE = "D001";
/**
 * 流程常量类
 */
FlowConstant = {};
//节点类型(结束节点)
FlowConstant.FLOW_TASK_ACTIVITY_TYPE_END = "END_EVENT";

//流程业务分类
FlowConstant.FLOW_MODEL_TYP_PRJ = "001";//立项
FlowConstant.FLOW_MODEL_TYP_PAY = "002";//正常放款
FlowConstant.FLOW_MODEL_TYP_PAY = "007";//提前放款
FlowConstant.FLOW_MODEL_TYP_PAY = "008";//特殊放款
FlowConstant.FLOW_MODEL_TYP_SPL_BANK = "004";//供应商账号
FlowConstant.FLOW_MODEL_TYP_INVOICE = "006";//开票

//审核状态
FlowConstant.FLOW_CHECK_STATE_NON = "0";//待提交
FlowConstant.FLOW_CHECK_STATE_IN = "1";//审核中
FlowConstant.FLOW_CHECK_STATE_PASS = "2";//审核通过
FlowConstant.FLOW_CHECK_STATE_NO_PASS = "3";//审核不通过

/**
 * 公共常量类
 */
ProjectConstant = {};

//=============产品类型============
ProjectConstant.PRD_TYE_LENGHT = 3; // 产品类型每级代码长度
ProjectConstant.PRD_CAR_CD = "007";//乘用车
ProjectConstant.PRD_BUS_CD = "008";//客车
//----------------------客户----------------------------//
ProjectConstant.CST_RL_SPONSOR="2";//担保人
ProjectConstant.CST_RL_CST="1";//客户
ProjectConstant.CST_TYP_CD_NP="1"//客户类型-自然人
ProjectConstant.CST_TYP_CD_LP="2"//客户类型-法人
//--------------------项目资产抵押------------------------------------//
ProjectConstant.CST_ASS_PROP_EQUI_CD="1";//资产属性设备
ProjectConstant.CST_ASS_PROP_BUIL_CD="2";//资产属性房屋
ProjectConstant.CST_ASS_PROP_OTH_CD="3"//资产属性其他
//------------------------项目报价---------------------------------------------//
ProjectConstant.LS_PD_UNT_MONTH='1';//月
ProjectConstant.LS_PD_UNT_YEAR='2';//年
ProjectConstant.LS_PD_UNT_DOUBLE_MONTH='3';//双月
ProjectConstant.LS_PD_UNT_SEASON='4';//季
ProjectConstant.LS_PD_UNT_HALF_YEAR='5';//半年
ProjectConstant.CAL_BASE_FINANCING = '2';//融资额
ProjectConstant.CAL_BASE_CONTRACT='1';//合同额
ProjectConstant.CAL_BASE_TOTAL_PRD_AMT='3';//设备款
ProjectConstant.CODE_END_NO_EQUAL="5";//期末不等额
ProjectConstant.CODE_BEGI_NO_EQUAL="6";//期初不等额

ProjectConstant.CODE_ANNINT_RATE_NUM_CD="01";//年利率小数位数
ProjectConstant.CODE_FLOAT_RATE_NUM_CD="02";//上浮比例小数位数
ProjectConstant.CODE_FEE_DECI_NUM_CD="03";//费用小数位数

ProjectConstant.CODE_DEF_FEE_DECI_NUM=2;//年利率默认小数位数
ProjectConstant.CODE_DEF_FEE_DECI_NUM=2;//上浮比例默认小数位数
ProjectConstant.CODE_DEF_FEE_DECI_NUM=2;//费用默认小数位数
ProjectConstant.CODE_DEF_AMT_DECI_NUM=2;//费用默认小数位数
//是否允许变更（5位标识位，1：租赁期数，2：支付方式，3：保证金处理方式，4：租赁期满处理方式，5：租赁年利率）
ProjectConstant.CODE_PRJ_QUAT_LS_PD=1;//租赁期数
ProjectConstant.CODE_PRJ_QUAT_PAY_WAY=2;//支付方式
ProjectConstant.CODE_PRJ_QUAT_DPST_HDL_WAY=3;//保证金处理方式
ProjectConstant.CODE_PRJ_QUAT_EXP_HDL_WAY=4;//租赁期满处理方式
ProjectConstant.CODE_PRJ_QUAT_ANNINT_RATE_PCT=5;//租赁年利率

/**
 * 计入首期款
 */
ProjectConstant.CODE_PRJ_QUAT_CNT_WAY_DOWNPAY = "1";
/**
 * 计入融资额
 */
ProjectConstant.CODE_PRJ_QUAT_CNT_WAY_FINANC="2";

/**
 * 计入合同额
 */
ProjectConstant.CODE_PRJ_QUAT_CNT_WAY_CONT="4";

/**
 * 计入期末款
 */
ProjectConstant.CODE_PRJ_QUAT_CNT_WAY_LAST="5";
/**
 * 计入租金
 */
ProjectConstant.CODE_PRJ_QUAT_CNT_RNT="6";
//----------------------------------抵押状态-------------------------------------------//
ProjectConstant.CODE_GUAR_STS_NONE=1;//抵押状态-未抵押
ProjectConstant.CODE_GUAR_STS_MTG=2;//抵押状态-已抵押
ProjectConstant.CODE_GUAR_STS_RELMTG=3;//抵押状态-已解押
ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_IN="1"
ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT="2"


//显示流程
function commShowFlow(_pInstId){
	if(StringUtils.isEmpty(_pInstId)){
		UIUtils.alertWarning(CommonConstant.C_P_INSTANCEID_NOT_HERE);
		return;
	}
	var params = "?pInsId="+_pInstId;
	var timestamp=new Date().getTime();
	Add_navTab('tab_cst_invoice_flow_'+timestamp,'查看流程','<%=path%>/flow/flow/toFlowShowPageFowBus.do'+params);
}